Having spent the last few days debugging a multi-threading where one thread was deleting an object still in use by another I realised that the issue would have been far easier and quicker to diagnose if I could have made ‘this’ volatile. It would have changed the crash dump on the system (Symbian OS) to something far more informative.
So, is there any reason why it cannot be, or shouldn’t be?
Edit:
So there really is no safe way to prevent or check for this scenario. Would it be correct to say that one solution to the accessing of stale class pointers is to have a global variable that holds the pointer, and any functions that are called should be statics that use the global variable as a replacement for ‘this’?
static TAny* gGlobalPointer = NULL;
#define Harness static_cast<CSomeClass*>(gGlobalPointer);
class CSomeClass : public CBase
{
public:
static void DoSomething();
private:
int iMember;
};
void CSomeClass::DoSomething()
{
if (!Harness)
{
return;
}
Harness->iMember = 0;
}
So if another thread deleted and NULLed the global pointer it would be caught immediately.
One issue I think with this is that if the compiler cached the value of Harness instead of checking it each time it’s used.
this is not a variable, but a constant. You can change the object referenced by this, but you can’t change the value of this. Because constants never change, there is no need to mark them as volatile.