Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

c++ - How do I delete an instance of the class?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...