The fact that the assignment syntax cannot be used to initialize an auto_ptr
from a raw pointer is a side effect of the constructor which takes a raw pointer being marked explicit. And the usual reason to mark a constructor as explicit is to prevent things like this:
void take_ownership(std::auto_ptr<ClassA> ptr) {
// the pointer is deleted when this function ends
}
void foo() {
ClassA obj;
take_ownership(&obj); // oops, delete will be called on a pointer to
// an object which was not allocated with new
}
The call to the take_ownership
function is an error there, because of the explicit classifier on the std::auto_ptr
constructor. Instead, you have to deliberately construct an auto_ptr
and pass that to the function.
void foo() {
std::auto_ptr<ClassA> ptr(new ClassA);
take_ownership(ptr); // okay
}
Of course this is not completely impervious to abuse (you can still pass a non-newed object to the constructor of auto_ptr
), it is at least easier to spot when an abuse is taking place.
By the way, std::auto_ptr
is deprecated. It is a very broken class (due to limitations in the language at the time it was introduced). Use std::unique_ptr
instead.