This diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) software development guidelines.
This diagnostic rule is relevant only for C++.
Applying std::move to an object of the const T type produces a value of the const T&& type. Under ideal passing conditions, this type will not invoke a constructor or move operator, since their signatures require the T&& mutable rvalue reference. According to the overload resolution rules, the compiler selects the copy constructor (if one is available). As a result, the object is copied rather than moved, which leads to an unintended copy of its resources.
The example:
void archiveData()
{
std::vector<std::string> archive;
const std::string technicalId = ....;
// ....
archive.push_back(std::move(technicalId));
}
The technicalId variable is marked with the const qualifier, meaning that the result of std::move(technicalId) will have the const std::string&& type. So, when resolving the overload for std::vector<std::string>::push_back, the version that takes const std::string & and results in a copy of the string will be selected.
The fix may look like this:
Option N1. If omitting the constness of the object being moved is not possible, the call to std::move needs to be removed:
void archiveData()
{
std::vector<std::string> archive;
const std::string technicalId = ....;
// ....
archive.push_back(technicalId);
}
Option N2. The object constness can be omitted:
void archiveData()
{
std::vector<std::string> archive;
std::string technicalId = ....;
// ....
archive.push_back(std::move(technicalId));
}
Removing the const qualifier changes the resulting expression type to std::string &&. This enables the compiler to successfully select the std::vector<std::string>::push_back overload that takes std::string &&, which then takes the resources from the passed object.
Was this page helpful?
Your message has been sent. We will email you at
If you do not see the email in your inbox, please check if it is filtered to one of the following folders: