Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporary object argument lifetime in a function

Tags:

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?

like image 711
Rick Avatar asked Jul 10 '18 08:07

Rick


People also ask

What is the lifetime of an object in c++?

C/C++ use lexical scoping. The lifetime of a variable or object is the time period in which the variable/object has valid memory. Lifetime is also called "allocation method" or "storage duration."

What is the lifetime of an object and how can you extend the lifetime of an object?

The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.

What is lifetime of an object?

In object-oriented programming (OOP), the object lifetime (or life cycle) of an object is the time between an object's creation and its destruction.

What are temporaries in c++?

In C++ temporaries are unnamed objects that compiler creates in various contexts. The typical uses include reference initialization, argument passing, evaluation of expressions (including standard type conversions), function returns, and exceptions (throw expressions).


1 Answers

Pre-C++17, sp is move-constructed from the temporary if the move is not elided to begin with. In either case, 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, if not elided, 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/move 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.

like image 78
Baum mit Augen Avatar answered Sep 21 '22 19:09

Baum mit Augen