Domanda

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;
}
È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top