c++ - 使用三元运算符和直接函数调用来延长生命周期?
问题描述
如果我有以下情况:
#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# - Zkemkeeper OnDisconnectedEvent 未在 C# 中触发
- mysql - SQL 付款总和
- python - 如何为 Keras 中的每个输出应用 sigmoid 函数?
- amazon-ec2 - 连接超时,EC2
- asp.net - 将图像逐像素与asp.net窗口形式中捕获的屏幕进行匹配
- angular - ng-bootstrap - 模态组件上的容器属性
- android - 为什么 RingtoneManager 返回的铃声 uri 在设置为媒体播放器的数据源时失败
- installation - 无法在 Ubuntu 18.04 中快速安装
- oauth-2.0 - 从 IOS 中的 AppAuth 获取刷新令牌时,OfflineImap 不同步邮件
- php - 我想提交表单而不重新加载页面并且没有 OK 消息