Domanda

Assume I have a C++ class like this:

class Container
{
private:
  union {
    Foo* foo;
    Bar* bar;
  } mPtr;
};

This class will be constructed on the stack. I.e. it won't be newed, so I can't just declare a zeroing operator new.

Can I use the initializer in the constructor to set mPtr to nullptr somehow?

Container()
 : mPtr(nullptr)
{
}

does not compile. Not even by adding a dummy union member of type nullptr_t.

Container()
 : mPtr.foo(nullptr)
{
}

doesn't compile, either.

È stato utile?

Soluzione

Use aggregate initialization, for example:

Container() : mPtr { nullptr }
{ }

I don't normally like posting links, but here is a good run through of this technique.

Altri suggerimenti

Depends on the compiler you are using. This should work, but VS 2013 does not support it.

Container(): mPtr{nullptr}
{
}

This does work however:

union {
   int* foo {nullptr};
   double* bar;
} mPtr;

Just default-initialise it.

Container()
 : mPtr()
{
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top