clang does not extend the lifetime of the temporary S()
while initializing the const lvalue reference. But it does extend the lifetime of S()
when initializing the rvalue reference. Why is that? If possible, I would like an answer with a quote from the Standard. Thanks.
#include <iostream>
struct B {
B() { std::cout << "B()\n"; }
~B() { std::cout << "~B()\n"; }
};
struct S
{
int a[3] = { 1, 2, 3 };
B b;
S() { std::cout << "S()\n"; }
~S() { std::cout << "~S()\n"; }
};
int main()
{
const int& r = S().a[0];
B&& rr = S().b;
std::cout << r << '\n';
std::cout << "end of main\n";
}
The output is:
B()
S()
~S()
~B()
B()
S()
1
end of main
~S()
~B()
EDIT I have doubts about the accepted answer to the question, of which this is considered to be a dupe. And this is because, the two other answers mention explicitly that GCC has a bug on this topic. And I agree with those answers, simply because GCC doesn't compile int &&r = S().a[0];
and it should, according to [cass.temporary]/6.
Besides this the OP said in his answer that GCC prints ~P extract
. Now it's printing extract ~P
. So its clear to me this is a valid question.