Say I have such simple functions:
struct Data {
string name;
string value; // Can be very long
};
// Use Data directly to avoid copy. (Not Data*)
unordered_map<size_t, Data> g_data;
// Should I use "const string& name, const string& value"?
void addData(string name, string value) {
// Should I use any std::move? Like:
// ... = {std::move(name), std::move(value)};
g_data[hash(name, value)] = {name, value};
}
// Returning as string seems obvious.
string generateData() {
// Some computation...
return value;
}
void test() {
addData(generateName(), generateDatA());
}
I know that the above code works. But I’m wondering whether I should use const string& in addData? I also wonder std::move can make it more efficient?
I’m using at least C++14, and C++17 is also enabled.
>Solution :
Yes, you should use std::move, but not like this. The proposed piece of code would try to hash moved-from strings (pre-C++17 it was unspecified if the strings would be already moved from at that point, see rule #20 here).
You should pre-calculate the hash and store it in a variable:
auto h = hash(name, value);
g_data[h] = {std::move(name), std::move(value)};
You should NOT pass string name, string value by const reference, since it would prevent you from moving them.