首页 > 解决方案 > 使用三元运算符和直接函数调用来延长生命周期?

问题描述

如果我有以下情况:

#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);
}

我没有得到令人惊讶的结果:

Running: 4
killed '4'

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

但是我遇到了 MSVC 16 (VS 19) 和 C++14 的崩溃...我想知道在上面的示例中是否没有生命周期延长。应该有,因为我将一个纯右值绑定A到一个A&&(the T&&) 上,它是一个右值引用。当绑定到 rvalue-reference 或 const lvalue-references 时,可以保证延长生命周期。

标签: c++c++14c++17object-lifetime

解决方案


推荐阅读