mardi 4 octobre 2016

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?

Aucun commentaire:

Enregistrer un commentaire