Is there a reason why the `explicit 'keyword is used in the std :: auto_ptr constructor?

This is the ctor used to create the std :: auto_ptr object from the standard pointer in the VS2008 compiler.

template<class _Ty> class auto_ptr { public: explicit auto_ptr(_Ty *_Ptr = 0) _THROW0() : _Myptr(_Ptr) {} private: _Ty *_Myptr; }; 

Is there any special reason why the explicit keyword is used above?

In other words, why can't I initialize auto_ptr with

std::auto_ptr<Class A> ptr = new Class A; ?

+4
source share
4 answers

Beware that otherwise you could inadvertently do something like:

 void foo(std::auto_ptr<int> p) { } void boo() { int* p = new int(); foo(p); delete p; // oops a bug, p was implicitly converted into auto_ptr and deleted in foo.... confusing } 

Unlike where you really clearly understand what is happening:

 void boo() { int* p = new int(); foo(std::auto_ptr<int>(p)); // aha, p will be destroyed once foo is done. } 
+7
source

Building std::auto_ptr is a transfer to ownership. It is best for everyone to participate in the transfer of ownership to be clear. For instance:

 void frobnicate(const std::auto_ptr<Class> & ptr); Class *instance = new Class(); frobnicate(instance); delete instance; 

If the constructor was implicit, then this code would compile, and it would be almost impossible to notice that it was wrong without checking the definition of frobnicate . Also, when using = to initialize is now more complicated, you can still use a different initialization syntax:

 std::auto_ptr<Class> instance(new Class); frobnicate(instance); 
+2
source

First, by resolving the immediate problem, you can initialize it as follows:

 std::auto_ptr<Class A> ptr(new A); 

Secondly, implicit conversion can do more harm than good, so it’s a good reflex to make designers callable with a single explicit parameter, to start with it, and then think about whether implicitness can be valuable.

+1
source

What is wrong with:

 std::auto_ptr<T> ptr(new T()); 

If you enable implicit conversion, you can trigger all sorts of problems with implicit clicks that are inserted where they are least expected.

0
source

Source: https://habr.com/ru/post/1381689/


All Articles