STL vector deallocation - c++

Given an STL vector of pointers, each element has to be deallocated before destroying the vector itself. Is there any technical implication that prevents the STL library for doing it automatically?
Thanks

The reason the STL doesn't do it for you is that it can't know whether or not it's supposed to. You might have a vector of pointers to arrays (in which case it needs to do delete[]), of pointers to regular objects (in which case it would need to do delete), or possibly memory from some custom allocator. Those pointers could also be shared with some other objects, in which case deleting them would cause those other objects to point at garbage data, leading to undefined behavior. Those pointers could also be to stack-allocated memory, in which case no deallocation is necessary.

you can store there pointers that shouldn't be deleted when vector is destructed
use vector of smart pointer (e.g. boost::shared_ptr) to receive automatic deallocation

If a vector contains pointers, it does not mean that the pointers point to dynamic memory. And if they do, should delete or delete[] be applied to each pointer? And what if the pointers points to objects created using placement new? All these question should be answered by the programmer, not by the library.

Related

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?
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.
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.
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.
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.

C++ When to use pointer to vector?

I have a problem about pointer and standard library use.
Let's create a new class
class Graph
{
std::vector<Edge> *edge_list;
//another way is
//std::vector<Edge> edge_list;
}
I already thought two reasons why I use pointer:
It's easy to manipulate the memory using new and delete
It can be passed by parameters easily.
However, we can pass by reference if we use vector.Then Reason 2 doesn't count.
So, Is it true if I am not strict with memory allocation, I don't need to use pointer to vector and other std container?
The implementation of std::vector contains 2 pointers:
The beginning of the allocated array
1 element after the end of the allocated array
Essentially, when you declare a vector it has no space allocated in the heap, but as you add elements this changes.
Note that std::vector manages the memory it uses, so there is no need for you to worry about new and delete (unnecessary complexity). As soon as it goes out of scope, it deallocates its memory (stack and heap).
As you said, a vector can be passed very easily by reference, which works the same way as a pointer for machine code, and it's more clear.

Difference between vector insert and assign

I read that the assign method clears the vector target indexes before assigning anything to it.Does that mean if we have a vector such as:
vector<foo*> somevector;
then the assign method would actually delete foo* before copying data to the target indexes.
then the assign method would actually delete foo* before copying data to the target indexes.
No, it will only delete pointer itself but will not delete objects which pointers pointing to.
You need to be careful when you use raw pointers in STL container. If you dynamically allocates elements in somevector, you endup leaking memory.
More practice way is to use smart pointers in STL container, dynamically allocated memory will be de-allocated in below case:
std::vector<std::unique_ptr<foo>> somevector;
No. std::vector will never call delete on stored pointers. It will simply destroy the object. In the case of a class objects with non-trivial destructors, destroying consists of calling that destructor. In the case of pointers, or any other trivially destructible object, destroying consists of doing nothing.
No, standard containers containing pointers to objects don't ever call delete on the pointers - you are responsible for doing this if/when necessary. This is why storing pointers is a bad idea.

About a vector defined in a function

Suppose a std::vector is defined in a function (i.e., on stack) and the vector is re-allocated (like by inserting data). Will any part of the vector be in heap? if yes, will it leave any garbage in heap when done executing the function? Thanks.
Will any part of the vector be in heap?
Yes: all of the elements in a std::vector are stored in a heap-allocated array.
Will it leave any garbage in heap when done executing the function?
No. The std::vector container, like all of the Standard Library containers, is responsible for cleaning up any objects that it creates.
Note, however, that if you dynamically allocate objects (e.g., using new) and store them in a container, then you are responsible for destroying those objects. To avoid having to clean things up yourself, you should avoid explicitly dynamically allocating objects wherever possible and use smart pointers everywhere else.

Can someone explain smart pointers in plain English?

Today I was asked about smart pointers in C++, and I can't find anywhere useful information about it..
Please, can someone tell:
What is smart pointers?
When do you need it?
Do you have any example where smart pointers is actually useful?
Thank you!
Primarily, smart pointers help you to:
Avoid leaks when exceptions are thrown. When an exception is thrown, you don't want any objects that are allocated earlier in the try block to be leaked. By wrapping them in smart pointers, which will be destroyed when the try block is exited, those objects will get properly destroyed.
Manage lifetime by reference counting owners to objects (i.e., the last one to destroy its smart pointer referencing a particular object actually deallocates the object). This is especially helpful in loosely coupled scenarios where it is not clear at what time the object should be destroyed, because users of the object do not know about each other.
A good example of where smart pointers are useful:
A vector of pointers to objects. By
making it a vector of shared pointers,
for example, the objects will
automatically be deallocated when the
vector is destroyed and/or objects are
removed. This automates object lifetime management and helps the user of the container avoid memory leaks.
Excerpt from Boost Smart Pointers (smart_ptr) lib:
Smart pointers are objects which store
pointers to dynamically allocated
(heap) objects. They behave much like
built-in C++ pointers except that they
automatically delete the object
pointed to at the appropriate time.
Smart pointers are particularly useful
in the face of exceptions as they
ensure proper destruction of
dynamically allocated objects. They
can also be used to keep track of
dynamically allocated objects shared
by multiple owners.
Conceptually, smart pointers are seen
as owning the object pointed to, and
thus responsible for deletion of the
object when it is no longer needed.
Smart pointers handle their own memory management by keeping track of how many references point to the memory. Once there are 0 references, it deletes the memory for you. Makes memory management easier.
Smart pointer general refers to a class that behaves like a pointer. You can use the class to store a pointer to memory that you allocate, and access data through the pointer.
The advantage is that, when used inside functions and methods, the smart pointer can be made to automatically deallocate the memory once the variable goes out of scope. Otherwise, this is a prime opportunity for a memory leak when functions fail to free all allocated memory.
For an example, check out http://msdn.microsoft.com/en-us/library/txda4x5t(VS.80).aspx.
A smart pointer is an object that dynamically allocates memory for the thing that it points to, and when the smart pointer goes out of scope it automatically deallocates the memory for the thing that it points to. It's useful when you want something that's deallocated when it goes out of scope, but that's too big to put on the stack (or has other issues that prevent it from being able to be put on the stack).
A smart pointer essentially manages memory allocated on the heap with an object allocated on the stack.
Because objects allocated on the stack have a fixed lifetime (i.e. within the scope they are declared) deallocation of the heap memory is deterministic and guaranteed to happen.
Smart pointers are basically objects that perform functions similar to pointers
they are used to lessen the allocation and deallocation time. For C++ one common example would be of auto_ptr