gpt4 book ai didi

c++ - 您如何分配返回的 auto_ptr?

转载 作者:搜寻专家 更新时间:2023-10-31 01:53:09 26 4
gpt4 key购买 nike

我正在尝试学习 auto_ptr,所以我编写了下面的代码,但它的结果是

..\src\main.cpp:23: 错误:'p1 = source()()' 中的 'operator=' 不匹配

我做错了什么?如何分配返回的 auto_ptr?

#include <stdio.h>
#include <memory>

using namespace std;

auto_ptr<int> source() {
int *i = new int();
*i = 100;
return auto_ptr<int>(i);
}

int main() {
std::auto_ptr<int> p1, p2;

p1 = p2;
p1 = source();

return 0;
}

最佳答案

你不能。

auto_ptr 是一个根本损坏的类。您必须使用 unique_ptr。问题的核心是auto_ptr不能复制,但是C++03不涉及move语义。 auto_ptr 实际拥有的语义是毫无用处的破烂黑客。

关于c++ - 您如何分配返回的 auto_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11511508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com