4

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.

Alexander
  • 2,581
  • 11
  • 17
  • 3
    https://stackoverflow.com/questions/35947296/about-binding-a-const-reference-to-a-sub-object-of-a-temporary – François Andrieux May 01 '18 at 19:36
  • FWIW g++ has the same behavior. – NathanOliver May 01 '18 at 19:36
  • 2
    It has nothing to do with lvalue vs rvalue. – Marc Glisse May 01 '18 at 19:38
  • @FrançoisAndrieux As you can see in some of the answers GCC has a bug on this. – Alexander May 01 '18 at 19:39
  • @NathanOliver If you change the const lvalue reference to an rvalue reference GCC doesn't compile. This is a bug in GCC. That's why I've chosen clang for this question. – Alexander May 01 '18 at 19:44
  • Alexander seems to be correct. GCC is now printing `extract ~P()`, while the OP reported in the other question that it was printing `~P() extract`. – Ayrosa May 01 '18 at 20:27
  • @Rakete1111 They are different questions. This one focus on why `S().a[0]` does not extend the lifetime. This is probably a Clang bug. – xskxzr May 02 '18 at 05:23
  • 1
    @xskxzr That's exactly what I mean. In [this other example](http://coliru.stacked-crooked.com/a/6cc73ece3d6f6cc4) I think I show this more clearly. But [clang HEAD](https://wandbox.org/permlink/RKJ1nMbD4eOKxI6h) in the Wand box seems to do it right. – Alexander May 02 '18 at 09:30

0 Answers0