How do you assign a returned auto_ptr?

家住魔仙堡 提交于 2019-12-11 01:18:05

问题


I'm trying to learn auto_ptr, so I wrote the code below but it results with

..\src\main.cpp:23: error: no match for 'operator=' in 'p1 = source()()'

What have I done wrong? How do you assign a returned 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;
}

回答1:


You cannot.

auto_ptr is a fundamentally broken class. You must use unique_ptr. The core of the problem is that auto_ptr cannot be copied, but C++03 does not involve move semantics. The semantics auto_ptr actually has are broken hacks good for nothing.



来源:https://stackoverflow.com/questions/11511508/how-do-you-assign-a-returned-auto-ptr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!