So I have a class called List which stores a vector of pointers to classes of type Object. List has a function called add which initialises an Object class and adds it’s pointer to the vector. I thought that once the add function ended that the Object class would be destroyed and accessing the pointer would cause an exception. When I wrote a test program to test this it turned out that the Object class was never destroyed.
Are classes initialised inside a function ever destroyed once the function ends?
When are classes automatically destroyed?
Depends how you’re creating the object. If you are doing it like this:
Then you are creating
objwith automatic storage duration. That means it will be destroyed when theaddfunction ends. The pointer you have pushed into the vector will no longer point to a validObject, so definitely don’t do this.You may, however, be doing this:
If you are, you are creating the
Objectwith dynamic storage duration and it will not be destroyed at the end of the function. The pointer you push into the vector will remain valid. However, if you do this, you need to remember todeletethe object at a later time. If you don’t, you’ll have a leak.The best option is to avoid using pointers at all, if you can. Just make the vector a
std::vector<Object>and copy objects into it:Or in C++11:
If you really need pointers, prefer smart pointers.