Reputation: 13840
Default initialization of a reference variable generates an error in GCC 4.8, but the following seems to compile and work without any warning/error.
struct Foo {
int &bar;
Foo(): bar(bar) { }
};
int main () {
Foo foo;
cout << foo.bar; // prints 0
return 0;
}
How does this compile? I'm particularly perplexed by this line:
Foo(): bar(bar) { }
Upvotes: 3
Views: 75
Reputation: 254751
It doesn't work, it's undefined behaviour.
It compiles because you can, in general, refer to a variable in its initialiser. This can have valid uses:
void * p = &p;
but in most cases leads to UB. You should get a warning about using an uninitialised value, if you enable sufficent warnings. In GCC, -Wuninitialized
(or -Wall
) should do it.
Upvotes: 4