Mr. Nicky
Mr. Nicky

Reputation: 1659

C++: Does vector of pointer elements automatically deallocate dynamic memory pointed by each pointer upon destruction?

The title is self explanatory - does the standard vector implementation take care of deallocating dynamic memory pointed to by all the pointers that are in the vector?

Upvotes: 0

Views: 721

Answers (4)

Jesper Juhl
Jesper Juhl

Reputation: 31467

No. When you destroy a std::vector it destroys all its elements (calls their destructor) and then deallocates the storage used by the objects. But a (raw) pointer does not have a destructor - destroying it does not deallocate the object it points to - it just destroys the storage used to hold the pointer itself.

If you had had a vector of smart pointers (std::unique_ptr or std::shared_ptr) then it would be a different matter. Those classes do have destructors and do deallocate what they point to upon destruction (unique_ptr always, shared_ptr if it's the last object pointing to the contained object, otherwise it just decrements its reference count).

Note: a std::unique_ptr is a very thin wrapper around a raw pointer, that is designed to almost optimize away completely. So, using it should have near or zero overhead over a raw pointer when optimization is enabled. So it'll give you the semantics you want with no overhead compared to doing the manual memory management - manually.

Upvotes: 5

Adrien Givry
Adrien Givry

Reputation: 965

No it doesn't. Containers are not reponsible of the memory management of raw pointers. It would be possible to automatically deallocate your pointer elements if they were smart pointers (RAII : https://fr.wikipedia.org/wiki/Resource_acquisition_is_initialization)

You can see a pointer as a simple integer. Its value represents a memory address. When the vector pointer element is deleted, the bytes allocated to store this address are freed. Thus, the memory address pointed by the pointer is lost (No more reference to it = memory leak).

Containers will never manipulate your instances (Free pointers, modify content). It can only call constructors (Specified one, copy, move...) and the destructor.

Upvotes: 3

Depends on the what pointers the vector is containing, for raw pointers like

std::vector<Something*> 

no, you have to do the cleanup yourself.

If the vector contains smart pointers, on the other hand, like std::unique_ptr

std::vector<std::unique_ptr<Something>> 

then the cleanup is taken care of for you.

Long story short: try to use smart pointers.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

No it doesn't.

If you want "self-deleting" pointers use smart pointers (std::unique_ptr or std::shared_ptr) or (depending on what the pointers are used for) a container such as std::vector, std::array or std::string.

Upvotes: 3

Related Questions