AutosarC++17_10-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
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | automated |
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 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#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 &¶m) {
Fn1(std::forward<T>(param)); // Compliant - forwarding forwarding reference
}
template <typename T> void Fn3(T &¶m) {
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.
- C++ Core Guidelines [10]: F.18: For ”consume” parameters, pass by X&& and std::move the parameter.
- C++ Core Guidelines [10]: F.19: For ”forward” parameters, pass by TP&& and only std::forward the parameter.
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¶
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
allow_forward_decltype¶
allow_forward_decltype : bool = False
decltype(..Template-Parameter..) as a
forwarding reference and do not produce violations on
std::forward(...) .