If you were allowed to write this:
std::unique_ptr<int> p = new int(5);
Then you would also be allowed to write these:
void Func1(std::unique_ptr<int> p);
Func1(new int(5));
std::unique_ptr<int> Func2() {return new int(5);}
Or the far more dangerous:
void Func1(std::unique_ptr<int> p);
int *pInt = new int(5);
Func1(pInt); //You no longer own the pointer anymore.
delete pInt; //You're now deleting a pointer you don't own.
That's not acceptable for obvious reasons. They don't want implicit conversion from naked pointers to unique pointers; if you want to create a unique_ptr
, you must be explicit about it: Func1(std::unique_ptr<int>(pInt));
Now, everyone can see that you're transferring ownership from yourself to the function.
Also, it's not an operator=
that would make this works. It's the explicit
on the single-argument constructor of unique_ptr
that stops the copy-initialization syntax from working.