ScopedPointer and destruction order issue


#1

I have something like this:

[code]

class SCOP1
{
void func();
};

class SCOP2
{
SCOP2(SCOP1* data) {m_data = data;}
~SCOP2() {m_data->func();}

SCOP1* m_data;
};

class BaseClass
{
ScopedPointer scop1;
ScopedPointer scop2;

BaseClass()
{
scop1 = new SCOP1();
scop2 = new SCOP2(scop1);
}
~BaseClass() {}

};[/code]

An SCOP2 object needs calling a function from SCOP1 object in SCOP2’s destructor. However if you run BaseClass’s destructor you don’t know what is going to be deleted before, so if SCOP1 was deleted then SCOP2 destructor crash.

Can I do something here if I want to use ScopedPointers? Or maybe this is a case where I must use delete and standart pointers?

Thanks


#2

…or you can just say

BaseClass()
{
   scop1 = new SCOP1();
   scop2 = new SCOP2(scop1);
}
~BaseClass()
{
   scop2 = nullptr;
   scop1 = nullptr;
}

#3

If you have a pointer to something that could be deleted elsewhere, you might also want to consider WeakReference.


#4

I like the idea of nullptr, thanks! :slight_smile: