See this example in [class.base.init]/11
struct A {
A() = default; // OK
A(int v) : v(v) { } // OK
const int& v = 42; // OK
};
A a1; // error: ill-formed binding of temporary to reference
A a2(1); // OK, unfortunately
Both clang and g++ compile the code (clang with a warning), but I'd like to understand why do they print 0
for the members a1.v
and a2.v
? See demo.
It doesn't matter that they print 0
.
For a1
, the initialization is ill-formed to begin with. For a2
, you're binding a reference to a temporary so you end up with a dangling reference. There's no significance to the 0
- it's whatever garbage memory the reference happens to point to at that point. Once you're violating preconditions, the program is undefined behavior.
Undefined behavior is undefined. There's no reason to expect a particular behavior for the print. For instance, gcc 7 prints 32764 while clang 4 prints 32765. Why? Why not.
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