Reputation: 197
I have seen many online articles and books but still i'm not able to reach the answer. The code is::
#include <iostream>
#include <vector>
using namespace std;
class a
{
public :
~a()
{
cout << "destroy";
}
};
int main()
{
vector <a*> *v1 = new vector<a*>;
vector <a> *v2 = new vector<a>;
return 0;
}
The answer is "no destructor call" but i not able to understand why?? thanks in advance.
Upvotes: 2
Views: 1339
Reputation: 5370
For a destructor to be called the object needs to be deleted.
When you have a local variable on the stack like
vector<a> v3;
The destructor of v3 will be called, which calls the destructors of the elements when it goes out of scope.
When you use pointers and they go out of scope the destructor to the object they point to is not called.
In your case you have manually allocated memory on the heap so you need to manually deallocate it.
So when you add
delete v2;
It will delete the vector v2 and it's elements.
v1 now is a pointer to a vector of pointers. So even
delete v1;
will not be enough because it just deletes the pointers in the vector not the object. You will have to call delete manually for each element inside the vector before deleting the vector.
Upvotes: 2
Reputation: 971
You're "new"ing your objects so in order to destroy them, you must delete them.
In your first line you're creating a pointer to vector of pointers, so you would have to delete the contents in order for the destructor to execute. Deleting the vector would empty them, but the memory for their contents would be forever lost.
In your second line you're creating a pointer to a vector of objects. When destroying your vector (by deleting it), the destructors would execute.
In any case, you're not filling your vectors with any data so there's no destruction to speak of.
Upvotes: 3