如何在C 中返回独特的所有权
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> :: 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)
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- 从函数返回范围视图时,带有std::span:中间对象所有权的C++Ranges-v3
- 如何在C 中返回独特的所有权
- 返回soliden_ptr私人会员数据而无需转移所有权
- 为原始指针(如所有权语义)返回unique_ptr的不良做法
- 从函数返回Unique_ptr时出现Unique_ptr所有权错误
- 如何在返回元组时转移unique_ptr的所有权?
- 如何返回指针的向量(和所有权)
- 从C#COM方法返回对象和内存所有权