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.
First, you only need to
deleteobjects created usingnew. Generally speaking, there is no order dependency for objects created bynew. 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.