Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a union of pointers to nullptr?

Tags:

c++

unions

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.

like image 359
hsivonen Avatar asked Dec 26 '22 12:12

hsivonen


1 Answers

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.

like image 130
Nim Avatar answered Jan 05 '23 17:01

Nim