I came up with the following example
std::shared_ptr<foo> a(new foo());
{
std::shared_ptr<foo> b = a;
std::cout << "before" << b.use_count() << "\n"; //returns 2
b.reset();
std::cout << "after" << b.use_count() << "\n"; //returns 0
}
std::cout << "Finished\n";
Now in the above code the second use_count statement returns zero. In that case isnt the destructor suppose to be called before printing out "Finished". Why is use_count in the second statement printing 0 ? I read that the definition of use_count is:
Returns the number of shared_ptr objects that share ownership over the same pointer as this object (including it).
If I did a reset() before use count that simply means that its reference count decreased by 1. Please correct me If I am wrong.
Here is my understanding of what is going on please correct me if I am wrong
std::shared_ptr<foo> a(new foo()); //reference count is 1
{
std::shared_ptr<foo> b = a; //reference count becomes 2
std::cout << "before" << b.use_count() << "\n"; //returns 2 //OK this I understand
b.reset(); //b smart pointer gives up its reference count so now it should be 1.
std::cout << "after" << b.use_count() << "\n"; //This should be 1 why is it 0 ?
}
std::cout << "Finished\n";
So my question is why is b.use_count() returning 0 ?
Aucun commentaire:
Enregistrer un commentaire