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?
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.
defaultaccording to the standard means "do whatever a generated default constructor would be - (even if that means implicit deletion)". However, many compilers warn about the implicit deletion and imo should continue to do so if the constructor is defaulted explicitly.