I tested the following code using Visual Studio 2017 version 15.3.1.
v.push_back(std::move(str1))
works as expected. It moves the contents of str1
into the vector.
str2
is a constant string. Since a constant string cannot be modified after it is created, I was expecting that the v.push_back(std::move(str2))
statement would result in a compiler warning. However, to my surprise there was no compiler warning. After stepped into it, I found that the overload of push_back(const T&)
was actually called. The std::move
in std::move(str2)
seems has no effect.
My question: Should a compiler warning be given for trying to move a constant object?
// Compiled with Visual Studio 2017 version 15.3.1
std::vector<std::string> v;
std::string str1 = "string 1";
v.push_back(std::move(str1));
// Call push_back(T&&). The contents of str1 is moved into the vector.
// This is less expensive, but str1 is now valid but unspecified.
const std::string str2 = "string 2";
v.push_back(std::move(str2));
// Call push_back(const T&). A copy of str2 is added into the vector.
// str2 itself is unchanged.