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.