为什么 unique_ptr<T>(T*) 是显式的?
以下函数无法编译:
std::unique_ptr<int> foo()
{
int* answer = new int(42);
return answer;
}
std::unique_ptr<int> bar()
{
return new int(42);
}
我觉得这有点不方便.使 std::unique_ptr<T>(T*)
显式的基本原理是什么?
I find this a bit inconvenient. What was the rationale for making std::unique_ptr<T>(T*)
explicit?
推荐答案
您不希望托管指针隐式地获取原始指针的所有权,因为这可能会导致未定义的行为.考虑一个函数 void f( int * );
和一个调用 int * p = new int(5);f(p);删除 p;
.现在假设有人重构 f
以获取托管指针(任何类型)并且允许隐式转换: void f( std::unique_ptr<int> p );
如果允许隐式转换,您的代码将编译但会导致未定义的行为.
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 call int * p = new int(5); f(p); delete p;
. Now imagine that someone refactors f
to 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.
以同样的方式考虑指针可能甚至不是动态分配的:int x = 5;f( &x );
...
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.
相关文章