C ++ - default initialization of a reference element - how does it work?

The default initialization of the reference variable generates an error in GCC 4.8, but the following seems to compile and work without warning / error.

struct Foo {
    int &bar;

    Foo(): bar(bar) { }
};

int main () {
  Foo foo;
  cout << foo.bar;  // prints 0
  return 0;
}

      

How does it compile? I am especially puzzled by this line:

Foo(): bar(bar) { }

      

+3


source to share


1 answer


It doesn't work, this behavior is undefined.

It compiles because you can generally refer to a variable in its initializer. This can have a valid application:



void * p = &p;

      

but in most cases results in UB. You should receive a warning about using an uninitialized value if you enable sufficient warnings. The GCC -Wuninitialized

(or -Wall

) should do it.

+4


source







All Articles