C++将字符串作为值或const String&amp传递。

发布于 2025-02-08 19:05:20 字数 769 浏览 0 评论 0原文

说我的功能很简单:

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());
}

我知道上述代码有效。但是我想知道我是否应该在adddata中使用const String&amp;?我也想知道std ::移动可以使其更有效吗?

我至少使用C ++ 14,并且还启用了C ++ 17。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纵情客 2025-02-15 19:05:20

是的,您应该使用std ::移动,但不像这样。提出的代码将尝试从字符串中移动(pre-c ++ 17,如果已经从那时已经移动,请参见规则#20 在这里)。

您应该将哈希进行预测并将其存储在一个变量中:

auto h = hash(name, value);
g_data[h] = {std::move(name), std::move(value)};

您不应通过const Reference传递字符串名称,字符串值,因为它会阻止您移动它们。

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.

等往事风中吹 2025-02-15 19:05:20

对于第一个问题:是的,使用参考更好,然后为每个adddata函数调用制作复制。如果您不使用它,则每个调用将创建名称和值的(不必要的)副本。

对于第二个问题:是的,移动可以更有效。

编辑:

有关我的答案的补充,请参阅下面的 @user17732522评论。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文