As far as I know that for both vector declarations as:
//TYPE 1
std::vector<cls> vec; //cls is user defined datatype(A class)
Memory for vector is allocated on stack and the memory of contents in the vector is allocated on heap.
It is true for the below declaration as well(Correct me if I am wrong):
//TYPE 2
std::vector<cls*> vec; //cls is user defined datatype(A class)
Now when the vector in Type 1 goes out of scope, memory is deallocated for the objects stored in it.
But what happens in type 2 if I insert elements as below(assuming that I have the proper overloaded constructor) and then the vector goes out of scope:
vec.push_back(new cls(5));
I explicitly tried calling clear but the destructor was not invoked. Will the memory be automatically be deallocated and the destructors be called. If not then how to achieve that.
Also, where is memory allocated for the vector as well as the contents if I declare vector as:
std::vector<cls*> *vec = new std::vector<cls*>;
vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.
No. The std::vector will automatically de-allocate the memory it uses. However, don't do this: std::vector< int *> Ints(2, new int (0));
Yes. vector::erase destroys the removed object, which involves calling its destructor.
This is why we have smart pointers.
{
std::vector<std::unique_ptr<cls>> vec;
// C++14 will allow std::make_unique
vec.emplace_back(std::unique_ptr<cls>(new cls(5)));
}
When the vector goes out of scope, the destructors of the unique_ptr
s will be called and the memory will be deallocated.
In your case, with the raw pointers, you'd have to delete
whatever you created with new
manually:
// Something along the lines of this.
for (auto&& elem : vec) {
delete elem;
}
Also, where is memory allocated for the vector as well as the contents if I declare vector as:
You're allocating the vector with new
, so it'll be on the heap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With