AUTOSAR C++14 Rule 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
Since R2020b
Description
Rule Definition
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.
Rationale
You can pass an object efficiently to a function by casting the object to an rvalue and taking advantage of move semantics.
If you are forwarding an rvalue reference to a function, use
std::move
to cast the object to an rvalue.If you are forwarding a forwarding reference (or universal reference) to a function, use
std::forward
to cast the object to an rvalue if and only if the object is bound to an rvalue. A forwarding reference might be bound to an rvalue or an lvalue. For the purposes of this rule, objects with typeauto &&
are considered as forwarding references.
Using std::move
with forwarding references might result
in an unexpected modification of an lvalue. Using std::forward
with
rvalue references is possible but it is error-prone and might increase the complexity of
your code.
Polyspace Implementation
Polyspace® flags the use of
std::move
to forward a forwarding reference to a function, including objects of typeauto &&
.Polyspace flags the use of
std::forward
to forward an rvalue reference to a function.Polyspace does not flag the use of
std::move
orstd::forward
if no forwarding to a function takes place. For instance, in this code snippet, no defect is raised on the use ofstd::move
with forwarding referenceb2
and the use ofstd::forward
with revalue referenceb1
.template <typename T1, typename T2> void func(T1& b1, T2&& b2) { const T1& b10 = std::forward<B>(b1); const T2& b20 = std::forward<B>(b2); const T1& b11 = std::move(b1); const T2& b21 = std::move(b2); }
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Language support library |
Category: Required, Automated |
Version History
Introduced in R2020b