Recently had some issues with static pointer. The code is part of a bigger project but esentially biols down to something like:
Class CustomClass {
public:
unsigned int SomeVar = 0;
};
....
namespace NS {
inline static CustomClass* CustomPtr = nullptr;
}
// Initialise the CustomPtr when app starting
...
if (NS::CustomPtr != nullptr) {
delete NS::CustomPtr;
NS::CustomPtr = nullptr;
}
NS::CustomPtr = new CustomClass();
...
//Use the CustomPtr
// Note the Usage always comes after the initialisation
NS::CustomPtr->SomeVar = 10; // <-- Throw read violation
There is a global namespace and that holds ppointer. When app start all pointer initialised on the heap (new) and ment to be available for the whole duration for the app. When new called, constructor executes and object saved in memory just fine, but the code result in a read violation when attempting to access any property of the CustomClass. Stepping in with the debugger turns out that the pointer is fine and can see it with its properties in the Debugger "Watch" part up until the line of code executes that dereferencing the pointer. On that line it changes to <struct in NULL> and becomes a null pointer.
The sulotion was to remove the "inline static" part. Now works fine. The question is why the "inline static" part broke everything?