Search code examples
c++-cli

Are managed pointers in c++/cli initialized to nullptr automatically using GCRoot?


I need to initialize to a variable only once in C++/CLI class accessible to managed code. Is a managed pointer initialized to nullptr when using gcroot? Specifically will the Initialize function below work as I expect? And only create the MyOtherClass once no matter how many times MyClass::Intialize is called?

class MyClass
{
public:
   void Initialize();

private:

#ifdef _MANAGED
    gcroot<MyOtherClass^> _myOtherClass;
#endif
};

void MyClass::Initialize()
{
    if(_myOtherClass == nullptr)
    {
        _myOtherClass = gcnew MyOtherClass();
    }
}

I'm using Visual Studio 2019. And the managed object accessing this is written in C#. I'm relatively new to CLI code. And I wasn't able to find the answer quickly by Googling it. And I'm sure someone in this community knows the answer.


Solution

  • Managed handles are default initialized to nullptr, per Default initialization: "when handles are declared and not explicitly initialized, they are default initialized to nullptr".

      if(_myOtherClass == nullptr)
    

    The above fails to compile with error C2088: '==': illegal for struct because gcroot wraps a GCHandle structure, which cannot be directly compared against nullptr.

    To check the target handle (not the wrapper handle), use the following, which works as expected.

      if(static_cast<MyOtherClass^>(_myOtherClass) == nullptr)