For the following code snippet, it shows different reference counts in the methods. Could someone explain why these values are different?
class Foo {
};
void f1( const std::shared_ptr<Foo>& ptr ) {
std::cout << "f1(): counts: " << ptr.use_count() << std::endl;
}
void f2( const std::shared_ptr<const Foo>& ptr ) {
std::cout << "f2(): counts: " << ptr.use_count() << std::endl;
}
int main() {
std::shared_ptr<Foo> ptr( new Foo );
std::cout << "main(): counts: " << ptr.use_count() << std::endl;
f1( ptr );
f2( ptr );
std::cout << "main(): counts: " << ptr.use_count() << std::endl;
return 0;
}
The corresponding output:
main(): counts: 1
f1(): counts: 1
f2(): counts: 2
main(): counts: 1
Note that std::shared_ptr<Foo> and std::shared_ptr<const Foo> are different types (i.e. the class template instantiations with different template type arguments are different types).
When you pass ptr (i.e. a std::shared_ptr<Foo>) to f2, it can't be bound to reference to std::shared_ptr<const Foo> directly; a temporary std::shared_ptr<const Foo> has to be constructed and then bound to the parameter ptr. The constructed shared_ptr shares ownership with the original shared_ptr, so use_count is increased to 2 in f2().
The temporary will be destroyed when f2( ptr ); ends; then use_count is decreased to 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With