为什么unique_ptr <t>(T *)显式?</t>

时间:2012-07-06 18:43:38

标签: c++ pointers c++11 type-conversion unique-ptr

以下函数无法编译:

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*)明确的理由是什么?

2 个答案:

答案 0 :(得分:27)

您不希望托管指针隐式获取原始指针的所有权,因为这可能最终导致未定义的行为。考虑一个函数void f( int * );和一个调用int * p = new int(5); f(p); delete p;。现在想象有人重构f以获取托管指针(任何类型)并允许隐式转换:void f( std::unique_ptr<int> p );如果允许隐式转换,则代码将编译但导致未定义的行为。

以同样的方式考虑指针甚至可能不是动态分配的:int x = 5; f( &x ); ...

获取所有权是一项非常重要的操作,最好明确说明:程序员(而不是编译器)知道是否应该通过智能指针管理资源。

答案 1 :(得分:19)

简答:

显式构造函数使得编写危险代码变得困难。换句话说,隐式构造函数可以帮助您更轻松地编写危险代码。

答案很长:

如果构造函数是隐式,那么您可以轻松地编写这样的代码

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. 

现在看危险部分:

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!

请阅读评论。它解释了上面代码片段的每个部分。

当使用原始指针调用f()时,程序员可能没有意识到f()的参数类型是std::unique_ptr,它将获取指针的所有权并且delete当它超出范围时。另一方面,程序员可以使用它,delete它甚至没有意识到它已经被删除了!这一切都是因为从原始指针到std::unique_ptr隐式转换。

请注意,std::shared_ptr具有explicit构造函数的原因完全相同。

相关问题