c++ - 为了支持 move 语义,函数参数应该由 unique_ptr、value 还是 rvalue 获取?

标签 c++ c++11 vector move unique-ptr

我的一个函数将 vector 作为参数并将其存储为成员变量。我正在使用对 vector 的 const 引用,如下所述。

class Test {
 public:
  void someFunction(const std::vector<string>& items) {
   m_items = items;
  }

 private:
  std::vector<string> m_items;
};

但是,有时items 包含大量字符串,所以我想添加一个支持 move 语义的函数(或用新函数替换该函数)。

我正在考虑几种方法,但我不确定选择哪一种。

1) unique_ptr

void someFunction(std::unique_ptr<std::vector<string>> items) {
   // Also, make `m_itmes` std::unique_ptr<std::vector<string>>
   m_items = std::move(items);
}

2) 传值和 move

void someFunction(std::vector<string> items) {
   m_items = std::move(items);
}

3) 右值

void someFunction(std::vector<string>&& items) {
   m_items = std::move(items);
}

我应该避免哪种方法以及为什么?

最佳答案

除非你有理由让 vector 存在于堆上,否则我建议不要使用 unique_ptr

无论如何, vector 的内部存储都存在于堆上,因此如果您使用 unique_ptr,您将需要 2 个间接度,一个用于取消引用指向该 vector 的指针,然后再次取消引用内部存储缓冲区。

因此,我建议使用 2 或 3。

如果您使用选项 3(需要一个右值引用),那么当您调用 someFunction.

从左值 move 的要求很繁重。

如果您的用户想要保留 vector 的拷贝,他们必须跳过铁环才能做到这一点。

std::vector<string> items = { "1", "2", "3" };
Test t;
std::vector<string> copy = items; // have to copy first
t.someFunction(std::move(items));

但是,如果您使用选项 2,用户可以决定是否要保留拷贝 - 选择权在他们自己手中

保留一份拷贝:

std::vector<string> items = { "1", "2", "3" };
Test t;
t.someFunction(items); // pass items directly - we keep a copy

不要保留拷贝:

std::vector<string> items = { "1", "2", "3" };
Test t;
t.someFunction(std::move(items)); // move items - we don't keep a copy

关于c++ - 为了支持 move 语义,函数参数应该由 unique_ptr、value 还是 rvalue 获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46549000/

相关文章:

c++ - #ifdef _WIN32 没有被检测到

c++ - 二维 vector 上的迭代器

c++ - 如何在类中将 vector 初始化为一定长度?

c++ - 有没有比编写存储对有状态分配器对象的引用的包装器分配器更好的方法来做到这一点?

c++ - 无法从测试中的项目链接目标文件

c++ - 指针 vector 和删除特定值

c++ - 执行外部程序的简单 C++ 跨平台方式

c++ - C++ 标准委员会是否打算在 C++11 中 unordered_map 破坏它插入的内容?

c++ - C++11、14、17 或 20 是否为 pi 引入了标准常量?

特定范围内向量的 MATLAB 绘图