Edit

Share via


Warning C26417

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 called code updates the target of the smart pointer object, and its caller expects to see such updates. Using a reference solely to reduce costs of passing a shared pointer is questionable. If called code only accesses the target object and never manages its lifetime, it's safer to pass a raw pointer or reference, rather than to expose resource management details.

Remarks

  • This check recognizes std::shared_pointer and user-defined types that 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);

  • a copy constructor or copy assignment operator (public and non-deleted);

  • a public destructor that isn't deleted or 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 that accepts a reference to a non-constant shared pointer can potentially reset or reassign that pointer.

Examples

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());
    // ...
}

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());
    // ...
}