Incorrect value forwarding
Forwarded object might be modified unexpectedly
Description
This defect occurs when:
You use
std::moveto forward a forwarding reference to a function, including objects of typeauto&&orT&&.You use
std::forwardto forward anrvaluereference 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
rvaluereference to a function, usestd::moveto cast the reference to anrvalue.If you forward a forwarding or universal reference to a function, use
std::forwardto cast the reference to anrvalueonly 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)