Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

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

   private:
   _Ty *_Myptr;
};

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

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

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

like image 598
Ayrosa Avatar asked Dec 27 '22 11:12

Ayrosa


1 Answers

Becasue you could otherwise unintentionally 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
}

In contrast with where you are actually explicitly aware of what is happening:

void boo()
{
    int* p = new int();
    foo(std::auto_ptr<int>(p)); // aha, p will be destroyed once foo is done.
}
like image 77
ronag Avatar answered Mar 08 '23 23:03

ronag