1

I have the following situation:

Foo1 foo1* = new Foo1(...);
Foo2 foo2* = new Foo2(foo1, ...);

or

Foo1 foo1(...);
Foo2 foo2(foo1, ...);

I need to delete Foo1 and Foo2. If I understand correctly, I should free memory in the reverse order it was allocated. So I should do:

delete(foo2);
delete(foo1);

I can't do this however, because foo1 is being set to NULL in foo2's destructor. So when I try to delete foo2, it's trying to delete a NULL reference and triggering an assert. Is there a way around this? The best solution here would allow me to still allocate the memory to the stack but it's definitely not necessary.


EDIT:

See this thread: Will a shared_ptr automatically free up memory?

Thank you for the responses. I was (clearly) wrong about what the problem was. I need to use a shared_ptr here because I can't change the API.

Foo1 *foo1 = new Foo1(...);
shared_ptr<Foo2> foo2(foo1);

Is the shared_ptr here going to handle freeing the memory used by foo1? If I understand correctly, I shouldn't have to call delete on foo1 correct?

I will ask as a seperate question and link to it.

Community
  • 1
  • 1
Justin
  • 447
  • 4
  • 10
  • 33
  • You shouldn't use `delete` with the second piece of code you provided. If you need it dynamically allocated, use a smart pointer and forget the deleting altogether. – chris Oct 02 '12 at 23:21
  • @chris I can't use the second piece because the freeing behind the scenes triggers an assert since the pointer in the Foo2 class to foo1 is NULL when it tries to free foo1's memory. – Justin Oct 02 '12 at 23:22

2 Answers2

7

First, you only need to delete objects created using new. Generally speaking, there is no order dependency for objects created by new. There may be a constructor/destructor dependency, though, such as if foo2 calls functions on foo1 in foo2's destructor. In this case, order of destruction is important.

Second, even if the foo1 pointer in foo2 is set to null, that is just the local copy of the pointer held in foo2. It will not effect other copies of the pointer. Setting foo1 to to null in foo2 is not a bad idea, since it signals the object should no longer be used but this is different to calling its destructor or freeing it.

akton
  • 14,148
  • 3
  • 43
  • 47
5

I should free memory in the reverse order it was allocated.

Uh, not for a general-purpose allocator, like the one powering new and delete.

I can't do this however, because foo1 is being set to NULL in foo2's destructor.

This is a giant pile of WTF. Why on earth would you have such a scheme? And don't even think about deleteing an object you did not new.

Just use smart pointers like a sane person and forget about all of this.

Puppy
  • 144,682
  • 38
  • 256
  • 465