Search code examples
c++shared-ptrsmart-pointers

What happens when we reset a shared_ptr when there are other shared_ptr alias constructed from it?


I am currently learning shared_ptr's alias constructor, and I wrote code like this

int main(){
    std::shared_ptr<Father> father = std::make_shared<Father>();
    std::shared_ptr<Son> son(father, &father->son);
    printf("%d\n", father.use_count());
    printf("%d\n", son.use_count());
    father.reset();
    printf("%d\n", father.use_count());
    printf("%d\n", son.use_count());
    printf("%d\n", father.owner_before(son));
    printf("%d\n", son.owner_before(father));
    return 0;
}

And it prints out

2
2
0
1
1
0

And I got lost here. In my opinion, after father.reset(), father should still have use_count = 1 rather than 0, because son is alias constructed from father, and it not destructed. From this post, the author also says father.use_count() is 1.

// the Foo still exists (ref cnt == 1) // so our Bar pointer is still valid, and we can use it for stuff

So why printf("%d\n", father.use_count()); prints out to be 0?


Solution

  • After father.reset(), father doesn't point to anything. It holds a null value (officially "there is no managed object").

    You are printing the use_count of nothing, not the use_count of the Father or Son object, and the use_count of a null pointer is 0.