When Smart Pointer Meets Const and Reference

const std::shared_ptr<T>& vs const std::shared_ptr<T>

1. Differences and Commons

Let’s first talk about const std::shared_ptr<T>&. This means a const reference to a shared_ptr.

  • There is no copy of the shared_ptr itself, so the reference count will not change.
  • const only applies to the shared_ptr, so the underlying data can be modified.
1
2
3
4
5
6
7
8
void Foo(const std::shared_ptr<T>& engine) {
engine->Run(); // OK

// engine.reset(); // Error
// engine = nullptr; // Error

engine->SetValue(1); // OK
}

Next, we have const std::shared_ptr<T>. shared_ptr is passed by value.

  • The reference count will change.
  • Same as above, const only applies to the shared_ptr, so the underlying data can be modified.
1
2
3
4
5
6
7
8
void Foo(const std::shared_ptr<T> engine) {
engine->Run(); // OK

// engine.reset(); // Error
// engine = nullptr; // Error

engine->SetValue(1); // OK
}

So, the short conclusion

Parameter Copies shared_ptr? Ref count change Can modify pointer? Can modify object?
const std::shared_ptr<T>& No No No Yes
const std::shared_ptr<T> Yes Yes No Yes

2. When to Use

How and when to use these two forms is mostly determined by ownership semantics. In many cases, const std::shared_ptr<T>& is preferred when the function only needs to use the shared_ptr during the call and does not need to acquire or retain shared ownership. It is also slightly more efficient because passing by const reference avoids copying the shared_ptr and therefore normally avoids incrementing and decrementing its reference count.

Author

Joe Chu

Posted on

2026-09-17

Updated on

2026-09-17

Licensed under

Comments