Link initialization in the default constructor C ++ 11

struct X {}; struct Y { Y() = default; X& x; }; 

works great in C ++ 11. I want to know how Y :: x actually gets initialized backstage?

+4
source share
3 answers

It does not compile in any major compiler. It will compile until an object of type Y is created.

If you create an object of type Y , the 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 a user-defined constructor, which is just an empty function, there is an error without creating an object.

Michael Burr is right. An implicit default constructor works fine. No diagnostic problems here, as I see.
+9
source

Even if you explicitly indicate that the value of Y() should be the default, the compiler must remove the default constructor under certain conditions (highlighting added):

8.4.2 / 4 Explicit default functions

Explicit default functions and implicitly declared functions are collectively referred to as default functions, and the implementation should provide them with implicit definitions (12.1 12.4, 12.8) , which may mean defining them as deleted

and

12.1 / 5 Constructors:

...

... By default, the default constructor for class X is defined as remote if:

  • any non-static data element without an element with alignment or equal value has a reference type

But it is not an error to define a remote function or constructor if you are not really trying to use it:

8.4.3 / 2 Remote definitions

A program that refers to a remote function implicitly or explicitly, in addition to claiming it, is poorly formed.

+11
source

It "works" if you do not make the object Y. After creating it, you will receive an error message:

(GCC 4.8.0)

error: uninitialized reference element in 'struct Y'

+8
source

All Articles