0

If I am having the following:

#include <iostream>
#include <string>
#include <type_traits>


struct A{
    ~A(){std::cout << "killed '" << a <<"'\n";}
    int a = 3;    
};

template<typename T>
void foo(T&& r){  // Is r still valid here???
  std::cout << "Running: " << r.a << "\n";   
}

int main()
{
 A* a = new A{3};
 
 foo(true ? A{4} : *a);
}

I get no suprising result:

Running: 4
killed '4'

http://coliru.stacked-crooked.com/a/b218bef991ef24d2

However I get a crash with MSVC 16 (VS 19) and C++14... I am wondering if in the example above there is no lifetime extension. There should be, since I am binding a prvalue A to a A&& (the T&&) which is a rvalue-reference. And lifetime extension is guaranteed when binding to rvalue-reference or const lvalue-references.

Gabriel
  • 8,990
  • 6
  • 57
  • 101
  • 2
    A temporary should be destroyed at the _end of the full-expression_. In this case, the temporary is `A{4}` and the full-expression is the entire statement with `foo` in `main`. Hence lifetime extension plays no role. https://eel.is/c++draft/class.temporary#4 – dyp Apr 19 '21 at 13:30
  • 1
    This runs fine on my VS 2019. – Hatted Rooster Apr 19 '21 at 13:45
  • 1
    This runs fine on my VS 2019 as well. It reminds me on some trouble I once faced: [SO: Pointer to member variable as static member](https://stackoverflow.com/q/64526453/7478597). Thus, according to that experience, carefully checking the settings of your compiler would be the last desperate idea of mine... – Scheff's Cat Apr 19 '21 at 13:50
  • I just go the subtlety: my `*a` and `A{4}` common type was a virtual interface which was the `T&& = ICallback&&`, which then results in uglyness and no life-time extension anymore I think... – Gabriel Apr 19 '21 at 14:00
  • Hmm. In my VS2019, I get the same result as above with the standard set to C++17; however, with C++14, the destructor gets called twice (for the '4' case). – Adrian Mole Apr 19 '21 at 14:08
  • This is definitely a Bug in MSVC: https://cppinsights.io/s/836f4b30 This with ` = 0` compiles here... – Gabriel Apr 19 '21 at 14:26
  • ... which it should not! Copy of abstract class is forbidden...) – Gabriel Apr 19 '21 at 14:33
  • https://godbolt.org/z/Mxzx1dqnc -> This falsely compiles. – Gabriel Apr 19 '21 at 14:41

0 Answers0