Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

class MyStrValArray {
    private:
    vector<char> p;
    public:
    void init(const int n);
    void clear();
    unsigned capacity();
    unsigned size(); 
    };


int main()
{
    MyStrValArray p1;

    ...

    if(p1.capacity() == p1.size())
    {
        MyStrValArray p2;
        p2.init(p1.size()*2);
        p2 = p1;
        p1.clear(); // I'm trying to delete the whole p1 instance, not the data inside p1.
    }

    return 0;
}

What I am trying to do is: when the memory of p1 is full, make another instance p2, with double of p1's size, copy all the data inside p1 to p2, and then remove p1.

How can I delete an instance of the class? If I use .clear(), I'm just deleting all the elements inside, not the instance itself. Is there any way to delete an instance?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
320 views
Welcome To Ask or Share your Answers For Others

1 Answer

you cannot 'delete' a local var and you do not need to do that, you want something like :

if(p1.capacity() == p1.size())
{
    p1.reserve(p1.size() * 2);
}

but your use of the reverse is quite useless, you can let std::vector to work to manage that by itself, except if you need to have iterator still valid after adding elements in a way compatible with the reserve size (see remarks on that answer)


About local var :

// here v does not exist
{
   // here v does not exist
   MyStrValArray v; // whatever the type
   std::cout << "blahblah" << std::endl; // here v may still not exist because of optimization because v still not necessary
   v.init(...); // here v exists
}
// here v does not exist

and the code generated by the compiler automatically calls the constructor and the destructor when needed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...