Reputation: 1802
Say I have a class:
struct foo{
foo* bar=nullptr;
};
Now if I use new to allocate memory like a chain:
foo instance;
instance.bar= new foo;
instance.bar->bar=new foo;
...
Then how can I delete all those children of instance
in a single call to delete the top level instance
, i.e. when I call destroy(instance); //dummy name
then all those dynamically allocated memory are all freed?
Upvotes: 2
Views: 116
Reputation:
You may get used to std::unique_ptr (or std::shared_ptr, if needed):
#include <memory>
struct foo{
std::unique_ptr<foo> bar;
};
int main() {
// Please do not use '_' as a variable name.
// (Some people do: #define _(T) gettext(T) // for gnu gettext support)
foo _;
_.bar = std::make_unique<foo>();
_.bar->bar = std::make_unique<foo>();
// ... the destructor will deallocate.
}
However, assuming foo
has a data member (structure) T, you may consider a single linked list:
#include <forward_list>
std::forward_list<T> foo_list;
Which leads to related questions like: Remove all nodes in linked list
Upvotes: 4
Reputation: 20264
First you should define your problem correctly.
I will take a general case and answer your question based on it:
This the solution based on the constraints:
struct foo{
foo()=default;
foo(foo const& other){
bar=new foo(*other.bar);
}
foo(foo&& other){
bar=other.bar;
other.bar=nullptr;
}
~foo(){
delete bar;
}
foo* bar=nullptr;
};
Upvotes: 0
Reputation: 1165
Add a destructor to your struct foo.
struct foo{
foo* bar=nullptr;
~foo() {delete bar;}
};
When the instance of foo goes out of scope, the destructor will be called and delete bar.
Upvotes: -1