在unique_ptr上使用强制转换操作符是危险的吗?

hun*_*ter 4 c++ unique-ptr c++11

我们有一个广泛的代码库,目前使用原始指针,我希望迁移到unique_ptr.但是,许多函数期望原始指针作为参数,并且在这些情况下不能使用unique_ptr.我意识到我可以使用get()方法传递原始指针,但这会增加我必须触摸的代码行数,而且我发现它有点难看.我已经推出了我自己的unique_ptr,它看起来像这样:

template <class T>
class my_unique_ptr: public unique_ptr <T>
{
  public:

    operator T*() { return get(); };
};
Run Code Online (Sandbox Code Playgroud)

然后每当我向一个期望原始指针的函数parm提供my_unique_ptr时,它会自动将其转换为原始指针.

问题:这样做有什么本质上的危险吗?我原本以为这将是unique_ptr实现的一部分,所以我认为它的遗漏是故意的 - 有谁知道为什么?

Moo*_*uck 7

隐式转换可能会发生许多丑陋的事情,例如:

std::unique_ptr<resource> grab_resource() 
{return std::unique_ptr<resource>(new resource());}

int main() {
    resource* ptr = grab_resource(); //compiles just fine, no problem
    ptr->thing(); //except the resource has been deallocated before this line
    return 0; //This program has undefined behavior.
}
Run Code Online (Sandbox Code Playgroud)


Att*_*ila 5

这是一样的调用getunique_ptr<>,但它会自动完成。您必须确保在函数返回后不存储/使用指针(unique_ptr<>在其生命周期结束时将删除它)。

还要确保您不要delete(甚至间接)调用原始指针。

还要确保的另一件事是您没有创建另一个获得指针所有权的智能指针(例如另一个uniqe_ptr<>) - 请参阅上面的删除注释

之所以unique_ptr<>没有做转换为你自动(并有你调用get()明确)是确保你有控制的,当你访问原始指针(避免可能悄无声息,否则发生上述问题)过

  • 如果不出意外,缺少转换可以防止新手灾难`unique_ptr&lt;int&gt; up(new int()); delete up;` 从编译:-) 我无法立即想到任何非新手错误的情况,在这种情况下,有人会错误地“删除”他们不拥有的资源的指针,以及需要调用 `get( )` 阻止他们这样做。 (3认同)