struct X {};
struct Y {
Y() = default;
X& x;
};
works fine in C++11. I wish to know how Y::x is actually initialized behind the scenes?
There are three steps to initializing a reference variable from scratch: declaring the reference variable; using the new operator to build an object and create a reference to the object; and. storing the reference in the variable.
Default constructors are one of the special member functions. If no constructors are declared in a class, the compiler provides an implicit inline default constructor. If you rely on an implicit default constructor, be sure to initialize members in the class definition, as shown in the previous example.
Default member initializer (C++11) [edit] This is the initialization performed when an object is constructed with no initializer.
Even though you explicitly indicate that Y()
should be defaulted, the compiler is obligated to delete the default constructor under certain conditions (emphasis added):
8.4.2/4 Explicitly-defaulted functions
Explicitly-defaulted functions and implicitly-declared functions are collectively called defaulted functions, and the implementation shall provide implicit definitions for them (12.1 12.4, 12.8), which might mean defining them as deleted
and
12.1/5 Constructors:
...
... A defaulted default constructor for class X is defined as deleted if:
- any non-static data member with no brace-or-equal-initializer is of reference type
But it's not an error to define a deleted function or constructor unless you actually try to use it:
8.4.3/2 Deleted defintions
A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed.
It doesn't compile in any major compiler. It will compile, until of creation of object of type Y
.
If you create object of type Y
, output of clang will be
error: call to implicitly-deleted default constructor of 'Y'
note: explicitly defaulted function was implicitly deleted here
Y() = default;
note: default constructor of 'Y' is implicitly deleted because field
'x' of reference type 'X &' would not be initialized
X& x;
When you declare user-defined
constructor, which is simply empty function, there is error, without creation of object.
Michael Burr is right. An implicitly-defaulted constructor works perfectly fine. There is no problems with diagnostic here, as I can see.
It "works" if you don't make a Y object. Once you make one you will get an error:
(GCC 4.8.0)
error: uninitialized reference member in 'struct Y'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With