A few hours ago I asked this question. I learned that std::vector deletes each of its elements when its destructor is called. Consider this program (a derivative of a previous example):
#include <vector>
#include <iostream>
class Bar {
int x;
public:
~Bar() {
std::cout << "~bar()" << std::endl;
}
};
class Foo {
std::vector<Bar*> v;
public:
Foo() {
this->v.push_back(new Bar());
this->v.push_back(new Bar());
this->v.push_back(new Bar());
}
~Foo() {
}
};
int main() {
Foo f;
Bar* b = new Bar();
// Bar::~Bar() called once
delete b;
// Bar::~Bar() not called three times as expected
return 0;
}
b’s destructor is called as expected; however, the destructors of the Bar* elements in f.v are not called. According to this, the destructor of each element of f.v should be called. What am I missing here?
The answer to this question is exactly the same as the answer to the last question. Deallocating a pointer does not call
deleteon it, so the thing it points to is not automatically destructed.Put another way,
Barhas a destructor, butBar*does not. So astd::vector<Bar>would invoke the destructor of each element.