Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do const shared_ptr<const T>& and const shared_ptr<T>& show different reference counts?

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
like image 770
Arup Raton Roy Avatar asked May 23 '17 01:05

Arup Raton Roy


1 Answers

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.

like image 180
songyuanyao Avatar answered Sep 28 '22 11:09

songyuanyao