C26417 NO_LVALUE_REF_SHARED_PTR

"Shared pointer parameter is passed by reference and not reset or reassigned. Use T* or T& instead."

C++ Core Guidelines: R.35: Take a shared_ptr<widget>& parameter to express that a function might reseat the shared pointer

Passing shared pointers by reference may be useful in scenarios where callee code updates target of the smart pointer object and its caller expects to see such update. Using a reference solely to reduce costs of passing a shared pointer is questionable. If callee code only accesses target object and never manages its lifetime, it is safer to pass raw pointer or reference, rather than to expose resource management details.

Remarks

  • This check recognizes std::shared_pointer and user-defined types which are likely to behave like shared pointers. The following traits are expected for user-defined shared pointers:
  • overloaded dereference or member access operators (public and non-deleted);
  • copy constructor or copy assignment operator (public and non-deleted);
  • public destructor which is neither deleted nor defaulted. Empty destructors are still counted as user-defined.
  • The action of resetting or reassigning is interpreted in a more generic way:
  • any call to a non-constant function on a shared pointer can potentially reset the pointer;
  • any call to a function which accepts a reference to a non-constant shared pointer can potentially reset or reassign that pointer.

Example

unnecessary interface complication

bool unregister(std::shared_ptr<event> &e) // C26417, also C26415 SMART_PTR_NOT_NEEDED
{
    return e && events_.erase(e->id());
}

void renew(std::shared_ptr<event> &e)
{
    if (unregister(e))
        e = std::make_shared<event>(e->id());
    // ...
}

Example

unnecessary interface complication - simplified

bool unregister(const event *e)
{
    return e && events_.erase(e->id());
}

void renew(std::shared_ptr<event> &e)
{
    if (unregister(e.get()))
        e = std::make_shared<event>(e->id());
    // ...
}