Please help me with this program:
struct U {
U(int *) noexcept;
private:
~U() noexcept;
};
struct B {
B();
~B();
U v; //ok
U w{nullptr}; //ok
U u = nullptr; //error
};
Here struct U
has a private destructor only for demonstration that the destructor is not really invoked by the compiler and to simplify the length of the code.
And struct B
has only declared a default constructor and destructor, so the compiler will not generate them in this translation unit.
Also struct B
has 3 fields: v
, w
and u
. There is no problem with the v
and w
fields, but for field u
the compiler issues an error about an inaccessible destructor for U
:
error: 'U::~U()' is private within this context
13 | U u = nullptr; //error
Demo: https://gcc.godbolt.org/z/YooGe9xq6
The questions are:
- If
B::B()
is not compiled in this translation unit, why is field default initialization considered at all? - Is the error because a temporary object is created for the initialization of the
u
field? (No mandatory copy elision?) - What is the difference between the
u
andw
cases then?