简体   繁体   中英

Will stl container free memory after deleting heap based object?

I am fairly new to C++, so I have got this question: I am know that stl containers do not deallocate memory from heap pointers, one need to deallocate it himself, and I know that containers call destructors of objects being deleted, but say we have this abstract code:

Object* pObject = new Object();
vector<Object>[i] = *pObject;

Now after vector gets destroyed will it actually free memory pObject pointing to? Or it will just call the destructor of Object, making it invalid and leaving the memory marked as "occupied" for memory manager?

Thank you.

You're not actually placing pObject in the std::vector , you're placing a copy of what pObject points to. Therefore the object in the std::vector and *pObject will be totally distinct.

When the std::vector is destroyed, it will call the destructor of this copy of the object, but your original object will be unaffected. Ie pObject will still point to a valid object, and will have to be delete 'd separately.

You have a vector<Object> hence, a vector of Object not Object* . The new is not needed at all in this case.

Standard containers will manage the memory they allocate, not yours. If you have a container of pointers to objects you have new ed, then you will need to delete them before the container goes out of scope.

If you want the container (with some allies) to manage the memory for you, use std::shared_ptr or std::unique_ptr . There are boost and tr1 equivalents if you compiler does not yet support C++11.

std::vector<std::shared_ptr<Object>> container;

The container will manage the smart pointers, and the smart pointers in turn manage the memory.

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