Arup Raton Roy Arup Raton Roy - 1 year ago 46
C++ Question

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

Answer Source

Note that std::shared_ptr<Foo> and std::shared_ptr<const Foo> 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 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download