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_ptritself, so the reference count will not change. - const only applies to the
shared_ptr, so the underlying data can be modified.
1 | void Foo(const std::shared_ptr<T>& engine) { |
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 | void Foo(const std::shared_ptr<T> engine) { |
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.
When Smart Pointer Meets Const and Reference
https://chuzcjoe.github.io/cpp/cpp-smart-pointer-meet-const-and-reference/
