如何在 C++ 中 return 唯一所有权

how to return unique ownership in c++

我无法从函数中移动 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,std::default_delete<_Ty>> &)': attempting to reference a deleted function

不是函数,是循环...

for (auto j : t)

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

for (auto const& j : t)