首页 > 解决方案 > 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++

解决方案


C++17 之前的版本,sp如果一开始就没有省略移动,则从临时移动构造。在任何一种情况下,sp都是资源的唯一所有者,因此使用计数正确地报告为 1。这是重载 10) †</sup> in this reference

虽然临时仍然存在,但如果没有被删除,它处于已移出状态并且不再持有任何资源,因此它不会影响资源的使用计数。

从 C++17 开始,由于保证复制/移动省略,不会创建临时文件,sp而是在原地构造。


†</sup> 来自所述参考文献的确切措辞:

shared_ptr10)从移动构造一个r。构造完成后,*this包含 的前一个状态的副本rr为空且其存储的指针为空。[...]

在我们的例子中,r指的是临时的和*thisto sp


推荐阅读