Home > Net >  C Pass a string as a value or const string&
C Pass a string as a value or const string&

Time:06-19

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related