C++ - Is destructor called when a vector holds objects?

眉间皱痕 提交于 2019-12-11 00:23:21

问题


If I dynamically allocate objects of a class inside a vector, is the destructor for each object called if I use clear()?


回答1:


Yes, they are all cleaned up properly.

From this link:

All the elements of the vector are dropped: their destructors are called, and then they are removed from the vector container, leaving the container with a size of 0.

The [sequence.reqmts] section of the upcoming standard also makes this clear:

a.clear() destroys all elements in a, invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator.




回答2:


What do you mean by "dynamically allocate" precisely? If you use a vector<foo> then you are fine. If you are putting pointers in via vector<foo*> then destructors will not get called, because the pointers don't have destructors per se.

Note, however, that in the vector<foo> case, you may find your constructors and destructors called a lot more than you expect e.g. when the vector is resized, because the vector will use them when moving the objects in memory if it needs to. You can use a Boost shared_ptr to get around that, though there is a small perf cost due to the reference-count bookkeeping.

My advice: use vector<foo> if the objects are cheap to copy and destroy, and vector<shared_ptr<foo> > if they're expensive or hard/impossible to copy. Never use vector<foo*> unless you specifically want to avoid having the vector handle memory management, and only then be careful; it's rarely a good idea IMHO.



来源:https://stackoverflow.com/questions/6326246/c-is-destructor-called-when-a-vector-holds-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!