C26416 NO_RVALUE_REF_SHARED_PTR

"Shared pointer parameter is passed by rvalue reference. Pass by value instead."

C++ Core Guidelines: R.34: Take a shared_ptr parameter to express that a function is part owner

Passing a shared pointer by rvalue reference is usually unnecessary. Unless it is an implementation of move semantics for a shared pointer type itself, shared pointer objects can be safely passed by value. Using rvalue reference may be also an indication that unique pointer is more appropriate since it clearly transfers unique ownership from caller to callee.

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

questionable constructor optimization

action::action(std::shared_ptr<transaction> &&t) noexcept // C26416
    : transaction_(std::move(t))
{}

action::action(std::shared_ptr<transaction> &t) noexcept  // also C26417 LVALUE_REF_SHARED_PTR
    : transaction_(t)
{}

Example

questionable constructor optimization - simplified

action::action(std::shared_ptr<transaction> t) noexcept
    : transaction_(std::move(t))
{}