0

is below code correct in regard to the static local variable? Will it be properly initialized? I heard that initialization may fail in case of DLLs!

#include <windows.h>

class SomeClass
{
    public:

        int anything;
};

BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID)
{
    static SomeClass *someClass = nullptr;

    switch (fdwReason) {
        case DLL_PROCESS_ATTACH:
            if (!someClass) {
                someClass = new SomeClass();
            }
            break;

        case DLL_PROCESS_DETACH:
            if (someClass) {
                delete someClass;
                someClass = nullptr;
            }
            break;
    }

    return TRUE;
}
no one special
  • 1,608
  • 13
  • 32
  • 1
    Where did you hear this? Why should it fail? – 463035818_is_not_an_ai Apr 24 '23 at 09:36
  • well, except the DllMain there is no other function that is executed on DLL load. So global variables will not be initialized. As static local variable needs auxiliary variable that indicate state of initialization, that variable is also not initialized. The question is if that is true? – no one special Apr 24 '23 at 09:41
  • related: https://stackoverflow.com/questions/75701/what-happens-to-global-variables-declared-in-a-dll – 463035818_is_not_an_ai Apr 24 '23 at 09:48
  • Just make it global. – Osyotr Apr 24 '23 at 09:54
  • `someClass` doesn't require dynamic initialization. It will be initialized to `nullptr` the moment the DLL is loaded from disk; it's in a data segment of the DLL file, with null initial value. But even if it did require dynamic initialization, it would have worked just fine; it'd be initialized the first time `DllMain` is called. – Igor Tandetnik Apr 24 '23 at 14:02

0 Answers0