Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 237
Nullptr Avatar asked Aug 16 '26 08:08

Nullptr


2 Answers

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.

like image 116
HolyBlackCat Avatar answered Aug 17 '26 22:08

HolyBlackCat


For the first question: yes, use a reference is better then make a copy for every addData function call. If you don't use it, each call will create a (unnecessary) copy of name and value.

For the second question: yes, move can be more efficient.

EDIT:

For a complement of my answer, please refer to @user17732522 comment below.

like image 42
Paulo Avatar answered Aug 17 '26 22:08

Paulo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!