Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do clang and g++ print 0 for a1.v and a2.v in this example in C++1z?

Tags:

c++

c++17

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.

like image 213
João Afonso Avatar asked Nov 17 '16 19:11

João Afonso


1 Answers

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.

like image 58
Barry Avatar answered Sep 21 '22 07:09

Barry