c++ - 右值引用

标签 c++ reference rvalue-reference

在尝试理解 here 中的右值引用时, 我无法理解两件事

  1. 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/

相关文章:

c++ - 什么决定临时对象的生命周期何时扩展到 const 引用或右值引用?

c++ - 如何在我的 C++ 程序中显示 Windows 的 "DLL not found"错误?

c++ - 使用 RapidJSON 解析文档时跳过某些字段

c++ - 将代码声明转化为文字(引用运算符和取消引用运算符混淆)

c++ - std::remove_reference 有什么意义

c++ - 如何延长表达式范围内临时变量的生命周期?

c++ - 运行时错误 : reference binding to misaligned address 0xbebebebebebebec6 for type 'int' ,,需要 4 字节对齐 (STL_vector.h)

c++ - 在 C++ 中将 HWND 转换为十六进制字符串

c++ - `const &&` 是否绑定(bind)到所有 prvalues(和 xvalues)?

const && 的 C++11 绑定(bind)规则