0

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?

kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80
  • 1
    Reference counts for `std::shared_ptr`'s apply to instances, not to references. – πάντα ῥεῖ Oct 04 '16 at 18:20
  • @πάνταῥεῖ Thank you. For version A, is the instance `p`? For version B, which is the existing instance? Is it the return value of `f()`? Maybe I did not fully understand references, which I thought is an alias of an object. – kgf3JfUtW Oct 04 '16 at 18:27
  • 3
    temporary lifetime extands with const reference. – Jarod42 Oct 04 '16 at 18:28
  • 1
    Related question that answers you question as well as point out relevant C++ Standard passages: http://stackoverflow.com/questions/2784262/does-a-const-reference-prolong-the-life-of-a-temporary – tkleczek Oct 04 '16 at 18:33
  • 1
    What do you think the reference is a reference *to*? – David Schwartz Oct 04 '16 at 20:25
  • @DavidSchwartz I think the reference refers to the temporary return value of `f()`. From [cppreference](http://en.cppreference.com/w/cpp/language/lifetime): The lifetime of a temporary object may be extended by binding to a const lvalue reference. Thanks @Jarod42 and @tkleczek – kgf3JfUtW Oct 04 '16 at 22:02

1 Answers1

1

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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524