2
votes

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?

3
Why are using _ as a variable name - not that descriptive.Ed Heal
@Ed Heal, I didn't come up with a name then, so you just edit it.YiFei
You could store all instances in some other container? Or you could add a destructor that deletes bar? Or think a bit more about the actual problem you want to solve, and come up with another solution or even another design? Or use a standard container to begin with?Some programmer dude
I'd suggest using smart pointers instead of manual memory management.Jesper Juhl

3 Answers

4
votes

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

0
votes

First you should define your problem correctly.

  1. What does copying foo mean? will every thing being deeply coped?
  2. Is this type movable?
  3. Can a child foo live without its parent?

I will take a general case and answer your question based on it:

  1. Copying is a deep copy.
  2. It is movable.
  3. Yes

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;
};
-1
votes

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.