Incorrect value forwarding
Description
This defect occurs when:
You use
std::move
to forward a forwarding reference to a function, including objects of typeauto&&
orT&&
.You use
std::forward
to forward anrvalue
reference to a function.
Consider the following code. In the function template callMethod
, the parameter param1
is a forwarding reference and the parameter param2
is an rvalue
reference. When forwarding these parameters to the function foo()
, the code incorrectly uses std::move
on the forwarding reference param1
and std::forward
on the
rvalue
reference param2
.
#include<string> #include<iostream> template <class T> class bar{}; template<typename T> void foo(std::string&& s, bar<T>&&){ //... } template <typename T> void callMethod(T&& param1, bar<T>&& param2) { foo(std::move(param1),std::forward<bar<T>&&>(param2)); }
T&&
or auto&&
, and rvalue
references are declared as &&
. Confusing forwarding references with rvalue
references results in incorrect value forwarding. Polyspace® does not report this defect if std::move
or
std::forward
does not forward a reference to a function. For instance,
this code does not forward the rvalue
reference b1
and
the forwarding reference b2
to another function. Using
std::move
with b2
or using
std::forward
with b1
does not cause a
defect.
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); }
Risk
Using std::move
with forwarding references can result in an
unexpected modification of an lvalue. Using std::forward
with
rvalue
references is error-prone and can increase the complexity of
your code.
Fix
If you forward an
rvalue
reference to a function, usestd::move
to cast the reference to anrvalue
.If you forward a forwarding or universal reference to a function, use
std::forward
to cast the reference to anrvalue
only if the object is bound to anrvalue
.
Examples
Result Information
Group: Programming |
Language: C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax:
INCORRECT_VALUE_FORWARDING |
Impact: High |
Version History
Introduced in R2020b
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)