【问题标题】:how to return unique ownership in c++如何在c ++中返回唯一所有权
【发布时间】:2018-04-24 12:44:29
【问题描述】:

我无法从函数中移动 std::vector<std::unique_ptr<..>>: MSVC 抱怨 (C2280) 试图引用已删除的函数。

这将如何工作?

#include <vector>
#include <iostream>
#include <memory>

using namespace std;

class foo {
public:
   int i;
};

vector<unique_ptr<foo>> test() {
   vector<unique_ptr<foo>> ret{};

   auto f = make_unique<foo>();
   f->i = 1;
   ret.push_back(move(f));

   return move(ret);
}

int main(int argc, char** argv) {
   auto t = test();
   for (auto j : t) {
// fails here: --^
      cout << j->i << endl;
   }

   getchar();
}

完整的错误信息如下:

'std::unique_ptr>::unique_ptr(const std::unique_ptr<_ty>> &)': 试图引用已删除的函数

【问题讨论】:

  • 错误信息指向foreach循环。
  • 对不起,在路上
  • return move(ret); return ret; 就足够了。
  • 您知道range-based for loop 是如何工作的吗?您尝试做的是复制向量中的值。
  • 我试图移动(ret),因为我认为复制可能会发生在那里。

标签: c++ smart-pointers unique-ptr


【解决方案1】:

不是函数,是循环...

for (auto j : t)

... 依次尝试为t 的每个元素复制初始化j。回想一下,普通的auto 表示值语义。请改用参考:

for (auto const& j : t)

【讨论】:

  • 非常感谢!看起来我只需要一个引用 thou(它可以在没有 'const' 关键字的情况下工作) - const 做了什么而 & 没有?
  • @santa - 防止您意外修改指针本身。默认情况下,我喜欢 const 正确的代码。严格来说,您没有必须在这里使用 const 引用,这只是一个很好的经验法则。
  • 谢谢 - 我的大脑刚刚搞砸了,认为引用是不可修改的指针 - 但它们是不可为空的指针 - const 使它们不可修改。
  • @santa • 它是对unique_ptr 的常量引用。 unique_ptr 本身就是一个对象。
  • @santa 它们确实是不可变的指针。裁判可能是可变的,也可能不是可变的 - 取决于引用声明中的 CV 限定符。
猜你喜欢
  • 1970-01-01
  • 2020-08-15
  • 2016-12-30
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2015-01-03
  • 1970-01-01
  • 2020-11-02
相关资源
最近更新 更多