在尝试理解 here 中的右值引用时, 我无法理解两件事
- If there are N strings in the vector, each copy could require as many as N+1 memory allocations and [...]
“N+1”中的这个 +1 是什么?
2.作者是如何突然得出以下指导原则的
Guideline: Don’t copy your function arguments. Instead, pass them by value and let the compiler do the copying.
我错过了什么吗?
最佳答案
What is this +1 in 'N+1'?
一个分配用于为新 vector 创建底层数组,然后是 N 个分配,一个用于 vector 中的 N 个字符串中的每一个。
How the author suddenly arrives at the below guideline
他争辩说,与其显式在函数内部制作拷贝,
std::vector<std::string>
sorted2(std::vector<std::string> const& names) // names passed by reference
{
std::vector<std::string> r(names); // and explicitly copied
std::sort(r);
return r;
}
当你将参数传递给函数时,你应该让编译器复制,
std::vector<std::string>
sorted2(std::vector<std::string> names) // names passed by value
{ // and implicitly copied
std::sort(names);
return names;
}
关于c++ - 右值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3623709/