ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 为了支持移动语义,函数参数应该由unique_ptr,value还是rvalue获取?

2019-09-30 10:05:49  阅读:243  来源: 互联网

标签:c c11 move vector unique-ptr


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

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

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

但是,有时项目包含大量字符串,因此我想添加一个支持移动语义的函数(或用新函数替换该函数).

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

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)按值传递并移动

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

3)右值

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

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

解决方法:

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

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

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

如果你使用选项3(需要右值引用),那么当你调用someFunction时,你要求你的类的用户传递一个右值(直接来自临时值,或者从左值移动).

从左值移动的要求是繁重的.

如果您的用户想要保留向量的副本,他们必须跳过箍来这样做.

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,c11,move,vector,unique-ptr
来源: https://codeday.me/bug/20190930/1835586.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有