The following functions do not compile:
std::unique_ptr<int> foo()
{
int* answer = new int(42);
return answer;
}
std::unique_ptr<int> bar()
{
return new int(42);
}
I find this a bit inconvenient. What was the rationale for making std::unique_ptr<T>(T*) explicit?
You don’t want a managed pointer to grab ownership of a raw pointer implicitly, as that could end up in undefined behavior. Consider a function
void f( int * );and a callint * p = new int(5); f(p); delete p;. Now imagine that someone refactorsfto take a managed pointer (of any type) and that implicit conversions were allowed:void f( std::unique_ptr<int> p );if the implicit conversion is allowed, your code will compile but cause undefined behavior.In the same way consider that the pointer might not be even dynamically allocated:
int x = 5; f( &x );…Acquisition of ownership is a important enough operation that it is better having it explicit: the programmer (and not the compiler) knows whether the resource should be managed through a smart pointer or not.