I was reading through this book C++ standard library book
And here is the part i can not understand:
Note that class auto_ptr<> does not allow you to initialize an object with an ordinary pointer by using the assignment syntax.
std::auto_ptr<ClassA> ptr1(new ClassA); //ok
std::auto_ptr<ClassA> ptr2 = new ClassA; //error
I don't understand why it is not allowed. What kind of pitfalls they were trying to avoid by not allowing initialization with assignment syntax
The fact that the assignment syntax cannot be used to initialize an
auto_ptrfrom 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:The call to the
take_ownershipfunction is an error there, because of the explicit classifier on thestd::auto_ptrconstructor. Instead, you have to deliberately construct anauto_ptrand pass that to the function.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_ptris deprecated. It is a very broken class (due to limitations in the language at the time it was introduced). Usestd::unique_ptrinstead.