Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Pass a string as a value or const string&

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading