AutosarC++17_03-A18.9.2

Forwarding values to other functions shall be done via: (1) std::move if the value is an rvalue reference, (2) std::forward if the value is forwarding reference

Required inputs: IR

Rationale

The std::move function unconditionally casts an rvalue reference to rvalue, while thestd::forward function does the same if and only if the argument was initialized with anrvalue. Both functions should be used as follows:

  • std::move should be used for forwarding rvalue references to other functions, asrvalue reference always bounds to rvalue
  • std::forward should be used for forwarding forwarding references to otherfunctions, as forwarding reference might be bound to lvalue or rvalue

Note that parameter of type “auto&&” is also considered as a forwarding reference forthe purpose of this rule.

Example
// $Id: A18-9-2.cpp 271927 2017-03-24 12:01:35Z piotr.tanski $
#include <cstdint>
#include <string>
#include <utility>
class A {
public:
explicit A(std::string &&s)
: str(std::move(s)) // Compliant - forwarding rvalue reference
{}

private:
std::string str;
};
class B {};
void fn1(const B &lval) {}
void fn1(B &&rval) {}
template <typename T> void fn2(T &&param) {
fn1(std::forward<T>(param)); // Compliant - forwarding forwarding reference
}
template <typename T> void fn3(T &&param) {
fn1(std::move(param)); // Non-compliant - forwarding forwarding reference
                 // via std::move
}
void fn4() noexcept {
B b1;
B &b2 = b1;
fn2(b2);            //   fn1(const B&) is called
fn2(std::move(b1)); //   fn1(B&&) is called
fn3(b2);            //   fn1(B&&) is called
fn3(std::move(b1)); //   fn1(B&&) is called
}
See Also
  • HIC++ v4.0 [8]:17.3.2 Use std::forward to forward universal references
  • Effective Modern C++ [12]: Item 25. Use std::move on rvalue references, std::forward on universal references.

Possible Messages

Key

Text

Severity

Disabled

forwarding_forwarding_reference

Use std::forward if the value is a forwarding reference.

None

False

forwarding_rvalue_reference

Use std::move if the value is a rvalue reference.

None

False

Options

allow_forward_decltype

allow_forward_decltype : bool = False

If set to true, consider decltype(..Template-Parameter..) as a forwarding reference and do not produce violations on std::forward(...).