如何分配返回的auto_ptr? [英] How do you assign a returned auto_ptr?

查看:82
本文介绍了如何分配返回的auto_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习auto_ptr,因此我在下面编写了代码,但结果为

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()()'

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

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;
}

推荐答案

您不能.

auto_ptr是一个从根本上中断的类.您必须使用unique_ptr.问题的核心是不能复制auto_ptr,但是C ++ 03不涉及移动语义.语义auto_ptr实际上已经是一无是处的破烂.

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.

这篇关于如何分配返回的auto_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆