Short answer:
The explicit constructor makes it difficult to write dangerous code. In other words, implicit constructor helps you to write dangerous code more easily.
Long answer:
If the constructor is implicit , then you could write such code easily:
void f(std::unique_ptr<int> param)
{
//code
} //param will be destructed here, i.e when it goes out of scope
//the pointer which it manages will be destructed as well.
Now see the dangerous part:
int *ptr = new int;
f(ptr);
//note that calling f is allowed if it is allowed:
//std::unique_ptr<int> test = new int;
//it is as if ptr is assigned to the parameter:
//std::unique_ptr<int> test = ptr;
//DANGER
*ptr = 10; //undefined behavior because ptr has been deleted by the unique_ptr!
Please read the comments. It explains each part of the code snippet above.
When calling f()
with a raw pointer, the programmer may not realize that the parameter type of f()
is std::unique_ptr
which will take ownership of the pointer and will delete
it when it goes out of scope. Programmer on the other hand may use it, and delete
it without even realizing that it has already been deleted! This all happens because of implicit conversion from raw pointer to std::unique_ptr
.
Note that std::shared_ptr
has explicit
constructor for the very same reason.