C++将字符串作为值或const String&amp传递。
说我的功能很简单:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您应该使用
std ::移动
,但不像这样。提出的代码将尝试从字符串中移动(pre-c ++ 17,如果已经从那时已经移动,请参见规则#20 在这里)。您应该将哈希进行预测并将其存储在一个变量中:
您不应通过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:
You should NOT pass
string name, string value
by const reference, since it would prevent you from moving them.对于第一个问题:是的,使用参考更好,然后为每个
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.