0

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?

Mr. Nicky
  • 1,519
  • 3
  • 18
  • 34
  • 2
    Possible duplicate of [What is a smart pointer and when should I use one?](https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one) – L. F. Jul 06 '19 at 01:16

4 Answers4

4

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 optimize away completely. So, using it should have 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.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
3

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

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.

Adrien Givry
  • 956
  • 7
  • 18
2

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.