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;
?
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With