Why use a static char buffer to instantiate a C ++ class loaded from a DLL

today i saw that this c ++ code istantiate class that is in DLL from EXE (after DLL load)

extern "C"
{
    DLL_EXPORT MyClass *CreateClass()
    {
        static char classBuffer[sizeof(MyClass)];

        return new ((void*)classBuffer)MyClass();
    }
}

      

I don't understand why we just don't use the new operator here, and instead we first declare this static buffer and then use it with the istantiation class. Any help is appreciated

+3


source to share


1 answer


Since it avoids the dependency on new

and delete

, but it still calls the constructor.

But this also means that you cannot have multiple instances of a class [in the same process, at least]. This may be deliberate to avoid more than one instance, or it may be a disadvantage. It all depends on what the purpose of the class itself is. But it would be bad to call this function more than once - and I think it should have some protection against that.



I feel that this is not an ideal way of solving the problem, but without understanding the general "background" of the class and this implementation, it is difficult to tell what other solutions exist and which one is correct.

+3


source







All Articles