consider something like this:
#include <iostream>
struct C {
C(double x=0, double y=0): x(x) , y(y) {
std::cout << "C ctor " << x << " " <<y << " " << "\n";
}
double x, y;
};
struct B {
B(double x=0, double y=0): x(x), y(y) {}
double x, y;
};
struct A {
B b[12];
A() {
b[2] = B(2.5, 14);
b[4] = B(56.32,11.99);
}
};
int main() {
const B& b = A().b[4];
C c(b.x, b.y);
}
when I compile with -O0 I'm getting the print
C ctor 56.32 11.99
but when I compile with -O2 I'm getting
C ctor 0 0
I know we can use const reference to prolong a local temporary, so something like
const A& a = A();
const B& b = a.b;
would be perfectly legal. but I'm struggling to find the reasoning for why the same mechanism/rule doesn't apply for any kind of temporary
EDIT FOR FUTURE REFERENCE:
I'm using gcc version 6.3.0
Your code should be well-formed, because for temporaries
(emphasis mine)
Given
A().b[4]
,b[4]
is the subobject ofb
and the data memberb
is the subobject of the temprorayA()
, whose lifetime should be extended.LIVE on clang10 with -O2
LIVE on gcc10 with -O2
BTW: This seems to be a gcc's bug which has been fixed.
From the standard, [class.temporary]/6