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.
Вопрос
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 new
ed, 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.
Решение
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.
Другие советы
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()
{
}