user3177112
user3177112

Reputation: 393

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.

Upvotes: 0

Views: 740

Answers (2)

Niall
Niall

Reputation: 30624

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 newed, 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.

Upvotes: 0

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. I.e. pObject will still point to a valid object, and will have to be delete'd separately.

Upvotes: 3

Related Questions