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++ 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."
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.
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.
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).
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
fromr
. After the construction,*this
contains a copy of the previous state ofr
,r
is empty and its stored pointer is null. [...]
In our case, r
refers to the temporary and *this
to sp
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With