Sam Shen Sam Shen - 2 months ago 8
C++ Question

Reference count for a reference to shared_pointer

I understand that the

shared_ptr
class automatically manages dynamic objects.

Here, I have a function
f
that returns a
const shared_ptr<int>
to an
int 2
.

I have two versions of
main
that differ in one place. Version A saves the return value of
f
into a shared pointer, while version B saves into shared pointer reference.

using namespace std;
const std::shared_ptr<int> f() {
const std::shared_ptr<int> ret = std::make_shared<int>(2);
return ret;
}

int main () {
const std::shared_ptr<int> p = f(); // A
// const std::shared_ptr<int> &p = f(); // B
cout << p.use_count() << *p << endl; // prints 1 2
return 0;
}


Both versions print
1 2
. I am okay with version A because
p
is the last
shared_ptr
pointing at the
int
, therefore
use_count
is
1
.

Question: Why is
use_count
equal to
1
for version B? Where is the last existing
shared_ptr
?

Answer

In C++ if you assign a temporary directly into a && or const&, reference lifetime extension kicks in and the temporary lasts as long as reference does.

This only works when your reference is a local variable1.


1 Or in certain cases in certain compilers where you use aggregate construction of structs. But don't use that, because it is one of the spots where a "transparent" forwarding constructor behaves fundamentally different than an aggregate, so otherwise innocuous changes later can break your code.