Reputation: 15756
Suppose:
struct Foo
{
int _b;
std::string _name;
};
class Bar
{
public:
vector<Foo>hold;
};
If a call to hold.clear()
isn't done on the destructor, does it means a memory leak?
I'm talking about objects, not pointer, because as far as I know push_back
creates a copy of the original object;
Upvotes: 0
Views: 70
Reputation: 1699
When an object is destroyed, so is all its members. So the (automatically generated) destructor of Bar will call the destructor of its hold member, which is going to call the destructors of its elements.
In summary: everything is destroyed automatically. This is a guarantee in C++: if you are manipulating objects by value, you have the guarantee that they are going to be destroyed when they get out of scope. The only thing you have to destroy explicitly are the objects that have been allocated on the heap (i.e. using new).
Upvotes: 1
Reputation: 227618
No, there are no memory leaks. When a Bar
goes out of scope, it's data member hold
is destroyed, and because std::vector
is well designed, all the elements it holds are destroyed.
struct Foo
{
int _b;
std::string _name;
~Foo() { std::cout << "Foo destructor"; }
};
class Bar
{
public:
vector<Foo>hold;
};
int main()
{
{
Bar b;
b.hold.push_back(Foo());
} // Foo, vector<Foo> and b instances destroyed here
}
Upvotes: 1