Destructing the Vector contents in C++
I have a std::vector
of Element*
. When will the destructor be called.
How is it different if it is a vector of Element
std::vector<Element*> vect;
..开发者_C百科
struct Element
{
Record *elm;
Element(Record *rec)
{
elm = new Record();
//...copy from rec
}
~Element()
{
delete elm;
}
};
I am using the vector as follows:
Element *copyElm = new Element(record);
vect.push_back(copyElm);
In the above code, how can I ensure there's no leak.
You could use a reference-counting pointer-wrapper class in your array, and the items will automatically get deleted whenever there are no more references to them. One such class is boost::shared_ptr
. You will also find it in some compiler's shipping C++ libraries because it is being added to a future version of C++.
std::vector<boost::shared_ptr<Element> > vect;
These classes wrap operator ->
, etc, so you can use them in most of the same ways that you'd used a normal pointer.
http://www.boost.org/doc/libs/1_45_0/libs/smart_ptr/shared_ptr.htm
Whenever you free the class Element
instance yourself. The vector will free the vector elements (the pointers), but not the class Element
objects pointed to. After all, the vector has no way to know if you have other pointers to the same object.
vector
will call release the memory of the object it is holding (i.e. pointers) but will not release the memory of the object it is pointing to. You need to release the memory of the Element
object yourself. If it was a vector<Element>
then whenever you do a push_back
a copy of the element is inserted into the vector. vector
guarntess that it will release the memory allocated to this copied object. But be aware with the current definition of Element
you will get a seg fault as you have not defined the copy ctor and assignment operator.
EDIT
If you for some reason don't want to use smart pointers, then only option is to write a release
function which goes through the entire vector and calls the delete
on the stored pointer.
In a vector of Element
, the destructor is called a lot. Whenever a node is assigned, the vector is sized down, the vector has to move in memory, or the vector goes out of scope/is destroyed, destructors are called on the elements before they are changed/discarded. Also, the copy constructor is called for assignment, and the default constructor is called to initialize each entry. Sorting such a vector will involve a lot of both copying and destroying.
In a vector of Element*
it is never called, unless you call delete
yourself.
Take a look at Boost shared_ptr
for a saner solution, or unique_ptr
if you have a compiler with relatively new features.
Destroying a pointer is always a no-op, and there are several good reasons why.
精彩评论