c++ - Temporary object argument lifetime in a function
问题描述
I've read several posts about temporary object's lifetime. And in a word I learn that:
the temporary is destroyed after the end of the full-expression containing it.
But this code is out of my expectation:
#include <memory>
#include <iostream>
void fun(std::shared_ptr<int> sp)
{
std::cout << "fun: sp.use_count() == " << sp.use_count() << '\n';
//I expect to get 2 not 1
}
int main()
{
fun(std::make_shared<int>(5));
}
So I think I have 2 smart pointer objects here, one is std::make_shared<int>(5)
, the temporary unnamed object and the other sp
which is a local variable inside the function. So based on my understanding, the temporary one won't "die" before completing the function call. I expect output to be 2 not 1. What's wrong here?
解决方案
C++17 之前的版本,sp
如果一开始就没有省略移动,则从临时移动构造。在任何一种情况下,sp
都是资源的唯一所有者,因此使用计数正确地报告为 1。这是重载 10) †</sup> in this reference。
虽然临时仍然存在,但如果没有被删除,它处于已移出状态并且不再持有任何资源,因此它不会影响资源的使用计数。
从 C++17 开始,由于保证复制/移动省略,不会创建临时文件,sp
而是在原地构造。
†</sup> 来自所述参考文献的确切措辞:
shared_ptr
10)从移动构造一个r
。构造完成后,*this
包含 的前一个状态的副本r
,r
为空且其存储的指针为空。[...]
在我们的例子中,r
指的是临时的和*this
to sp
。
推荐阅读
- visual-studio-code - 如何在 Visual Studio Code 中抑制集成终端上的信息
- create-react-app - 如何使用 TSLint 查看反应脚本 ESLint 错误
- android - 为音乐应用程序制作循环播放按钮时出现问题
- c# - 如何检测事件引用泄漏
- inheritance - 在多级层次结构的情况下,杰克逊 jsonsubtypes 字段不绑定
- flutter - 如何在颤振中创建一个垂直按钮?
- maven - 将 nexus 凭据绑定到 jenkins 构建中的 maven 部署作业
- conda - 如何让snakemake默认使用--use-conda?
- prestashop - 如何添加:在 Prestashop 中使用 TTC 而不是 HT
- pdo - Eclipse/PHP:PDO 无法解析为类型