2

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;
}
Some Noob Student
  • 14,186
  • 13
  • 65
  • 103
  • 1
    Don't use auto_ptr, it's considered flawed and obsolete. Use unique_ptr instead. – Philipp Jul 16 '12 at 19:52
  • 1
    Your program actually compiles without a hitch with GCC 4.7.1. Seems to be a broken MS compiler and library again. Try the copy constructors, they may have implemented them – fork0 Jul 16 '12 at 19:55
  • The code you've posted compiles without errors on both VS2010 and [gcc-4.3.4](http://ideone.com/lE8zO). – Praetorian Jul 16 '12 at 20:09
  • I was trying to port a library over to qnx, it implemented similar functionality as the above program, where it gave this error. Trying this later on GCC 4.6.3, it may compile fine but gives seg fault at runtime. – Some Noob Student Jul 16 '12 at 21:22
  • If you have 4.6.3, you have move semantics and `unique_ptr` so the point is moot. – Puppy Jul 17 '12 at 04:29

1 Answers1

3

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.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 1
    What do you mean by *you cannot*? The whole problem with `auto_ptr` is that it allows copy construction and assignment. – Praetorian Jul 16 '12 at 20:28
  • That's not a real copy. Hence why it's so broken. – Puppy Jul 16 '12 at 22:15
  • Yes, it's not a real copy in the sense that it modifies the right hand argument. I'm not disagreeing with you that `auto_ptr` is broken, it definitely is, and `unique_ptr` should be used instead. But the OP's code is perfectly valid and compiles without errors (as it should). So your answer is incorrect because you claim that one `auto_ptr` cannot be assigned to another. – Praetorian Jul 16 '12 at 22:25
  • Have you tried running it? On GCC4.6.3 this code may compile fine, but running it yields seg fault, perhaps DeadMG's claim is legit. – Some Noob Student Jul 17 '12 at 00:45
  • -1, the OP is asking about assignment from an rvalue, the case `auto_ptr` is designed for, and works well for without needing C++11. @SomeNoobStudent, it runs fine for me with all versions of GCC. If it segfaults for you it's not because of `auto_ptr` – Jonathan Wakely Jul 27 '12 at 11:59