Muokkaa

Jaa


Warning C26416

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

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

Passing a shared pointer by rvalue reference is rarely necessary. Unless it's 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 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.

Examples

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)
{}

Questionable constructor optimization - simplified:

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