C26418 NO_VALUE_OR_CONST_REF_SHARED_PTR

"Shared pointer parameter is not copied or moved. Use T* or T& instead."

C++ Core Guidelines: R.36: Take a const shared_ptr<widget>& parameter to express that it might retain a reference count to the object

If shared pointer parameter is passed by value or reference to a constant object it is expected that function will take control of its target object’s lifetime without affecting of the caller. The code should either copy or move the shared pointer parameter to another shared pointer object or pass it further to other code by invoking functions which accept shared pointers. If this is not the case, then plain pointer or reference may be feasible.

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.

Example

unnecessary interface complication

template<class T>
std::string to_string(const std::shared_ptr<T> &e) // C26418, also C26415 SMART_PTR_NOT_NEEDED
{
    return !e ? null_string : e->to_string();
}

Example

unnecessary interface complication - simplified

template<class T>
std::string to_string(const T *e)
{
    return !e ? null_string : e->to_string();
}