Possible Duplicate:
deleting dynamically allocated object that contains vector in C++ STL
I have a struct like this
struct foo {
vector<int> myvector;
};
Now, I create a pointer to foo, resize and insert some elements into the vector.
foo *myfoo = new foo;
myfoo->myvector.resize(100);
myfoo->myvector.push_back(0);
myfoo->myvector.push_back(1);
... // and so on
Now, before myfoo goes out of scope, I would have to deallocate the memory allocated to it with
delete myfoo;
My question is whether this would take care freeing myvector also? I have this particular query because now that myvector is resized, the STL library would presumably allocated the container in the heap. So, when I free up myfoo, I wouldn't want the memory allocated to myvector leaking.
Yes, deleting myfoo will destroy all of its members too, which includes the std::vector. It's important to note that if you had pointers inside foo, only the pointers would be destroyed, not the objects they point to (unless of course you defined a destructor that did that job for you - which you should!).
It is mandated by the standard that after execution of the destructor, any non-static data members are destroyed also (§12.4/8):
After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class
Xcalls the destructors forX's direct non-variant non-static data members, the destructors forX’s direct base classes and, ifXis the type of the most derived class (12.6.2), its destructor calls the destructors forX's virtual base classes.
The class foo has a defaulted destructor because no user-declared destructor is defined (§12.4/4):
If a class has no user-declared destructor, a destructor is implicitly declared as defaulted (8.4).
The destructor of myfoo is called when it is deleted (§5.3.5/6):
If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted.
A delete-expression is an expression of the form:
::optdeletecast-expression
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With