2

According to this blog, the following code should be well defined:

#include <iostream>

struct Foo{

  Foo()=default;
  Foo(Foo && f)=default;
  Foo(Foo const& f)=delete;
  ~Foo(){std::cout << __func__ << '\n';}

  //value to bind to
  int a=123;
};

int main(){

  const int& ptr = Foo{}.a;
  std::cout << ptr << '\n';
}

Although Foo{} creates a temporary, the binding with const& should prolong Foo's lifetime.
The temporary should last as long as the reference.

The article states:

Q3: When the reference goes out of scope, which destructor gets called?
A3: The same destructor that would be called for the temporary object. It’s just being delayed.

If that is the case, why does the program print:

~Foo
123

instead of:

123
~Foo

It seems that Foo is being destructed before I use the reference.

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • 1
    Lifetime extension only happens when a prvlaue (a "temporary object") is bound to a reference. You're not doing that. You would need to say `const Foo& ptr = Foo{};` to extend the lifetime. – Kerrek SB Jul 07 '16 at 09:17
  • 3
    @KerrekSB: Why not make this an answer? – Christian Hackl Jul 07 '16 at 09:18
  • The temporary here is Foo{}, you're binding something else than that therefore no lifetime extension happens. – Borgleader Jul 07 '16 at 09:18
  • @Borgleader: Specifically, access of a non-constant data member of a prvalue produces an xvalue, not a prvalue. (This was only clarified in C++14. It was just kind of broken before.) – Kerrek SB Jul 07 '16 at 09:19
  • @ChristianHackl: Meh... sometimes simple observations don't really warrant an answer. – Kerrek SB Jul 07 '16 at 09:20
  • Section §12.2/5 from standard explains your doubts. More brief explentation can be found on H. Sutters blog: https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ – paweldac Jul 07 '16 at 09:21
  • What compiler are you using? [Clang](http://rextester.com/REJ5523) works well. – songyuanyao Jul 07 '16 at 09:25
  • And see [this comment](http://stackoverflow.com/questions/38226443/const-reference-to-member-of-temporary-object/38227096#comment63877160_38227096) if you're using GCC. – songyuanyao Jul 07 '16 at 09:27
  • @KerrekSB: No, they always do, if they answer the question. Comments are not subject to the peer review mechanisms. – Lightness Races in Orbit Jul 07 '16 at 09:56

0 Answers0