AutosarC++18_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
std::move
for rvalue references and std::forward for forwarding references (template
parameters that deduce both lvalue and rvalue). Using the wrong utility defeats move semantics
or creates unnecessary copies, effectively reducing performance.
Bad code (std::move with forwarding reference):
void Process(std::string&& str);
void Process(const std::string& str);
template<typename T>
void Forward(T&& value) { // Forwarding reference: T&& accepts both lvalue and rvalue
Process(std::move(value)); // ERROR: std::move unconditionally casts to rvalue,
// ignoring what T deduced to. When called with an lvalue, std::move silently steals
// from the caller's object.
}
int main() {
std::string s = "hello";
Forward(s); // lvalue call: caller expects s to remain valid afterward,
// but s is moved-from and thus left in an unspecified state
Forward(std::string("hello")); // rvalue call: happens to work, but std::forward is still correct
}
Good code (std::forward for forwarding reference):
template<typename T>
void Forward(T&& value) {
Process(std::forward<T>(value)); // OK: preserves lvalue/rvalue
}
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: 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(...) .