简体   繁体   中英

deleting a vector of pointers vs. object in c++

I have a vector of pointers to an object (I have them as pointers because I will be swamping the positions around a lot, and I would imagine it would be a lot faster to just swap the pointer, rather than swapping around the whole object.

Anyway, I will ultimately need to delete the vector, but the objects that it points to still need to be valid. The documentation seems to say that it will call the destructor on every object in the vector. This makes sense when it's an array of objects, but if the array is an array of pointers to objects, will the objects that the pointers point to also be deleted, or do I need to delete them manually?

If they are deleted automatically, is the only way to keep the objects around (say they were used in a different vector) is to actually copy the objects to another location, and have the pointers in the vector point to those objects (rather than the originals)?

Thank you.

Calling a destructor on a pointer value does nothing. (On the other hand, calling delete on a pointer value runs the destructor for the pointed-to object, and frees the memory.)

In the case of an array of pointers to objects, you must free the objects manually if that's what you want.

如果你有一个指针向量,如果删除(或清除)向量,实际对象应该仍然存在。

您可以在向量中使用智能指针,例如Boost shared_ptr

It will indeed destruct any objects in the container. However, since all the objects in your container are pointers, that won't do much of anything.

Reading your question, that sounds like exactly what you want it to do, so you are good.

It does not matter - that's the reason for the delete keyword. If you go out of scope, then the object's destructor is called. If a pointer goes out of scope, then it tends to be a memory leak. The same applies here, so you will not have to do anything special.

They will continue to exist.

Anyway, I will ultimately need to delete the vector, but the objects that it points to still need to be valid. The documentation seems to say that it will call the destructor on every object in the vector. This makes sense when it's an array of objects, but if the array is an array of pointers to objects, will the objects that the pointers point to also be deleted, or do I need to delete them manually?

First, read this: http://crazyeddiecpp.blogspot.com/2010/12/pet-peeve.html

Now ask yourself, does the documentation say that vector deletes every object that every object it contains points at?

If you can answer that question with 'No' then there you have it.

If you can answer that question with 'Yes'...well...try different documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM