Temporary object argument lifetime in a function

  • A+
Category:Languages

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?

 


Pre-C++17, sp is move-constructed from the temporary even if the move is not elided to begin with. Thus, sp is the sole owner of the resource, so the use count is rightly reported as 1. This is overload 10) in this reference.

While the temporary still exists, it is in a moved-from state and no longer holds any resource, so it doesn't contribute to the resource's use count.

Since C++17, no temporary is created thanks to guaranteed copy elision, and sp is constructed in place.


Exact wording from said reference:

10) Move-constructs a shared_ptr from r. After the construction, *this contains a copy of the previous state of r, r is empty and its stored pointer is null. [...]

In our case, r refers to the temporary and *this to sp.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: