如何在C 中返回独特的所有权

how to return unique ownership in c++

本文关键字:所有权 返回      更新时间:2023-10-16

我不能从函数中移动 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> :: simolor_ptr(const std :: simolor_ptr&lt; _ty,std :: default_delete&lt; _ty>>>>&amp;(':尝试引用已删除的函数

它不是功能,而是循环...

for (auto j : t)

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

for (auto const& j : t)