Why is this an issue?
Forwarding references are a special kind of references that both ignore and preserve the value category of a function argument,
making it possible to forward it by means of std::forward
.
Any code using such a reference for any other purpose than forwarding is actually ignoring rvalue-ness and const-ness of the associated
parameter.
Noncompliant code example
#include <utility>
#include <string>
#include <iostream>
template<typename TP> void f( TP&& arg ) {
std::string s(arg);
}
int main() {
std::string s("test");
f(std::move(s));
std::cout<<"f:"<<s<<std::endl; // output is "f:test"
return 0;
}
Compliant solution
#include <utility>
#include <string>
#include <iostream>
template<typename TP> void f( TP&& arg ) {
std::string s(std::forward<TP>(arg));
}
int main() {
std::string s("test");
f(std::move(s));
std::cout<<"f:"<<s<<std::endl; // output is "f:"
return 0;
}
Resources