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实现的一部分,所以我认为它的遗漏是故意的 - 有谁知道为什么?
隐式转换可能会发生许多丑陋的事情,例如:
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)
这是一样的调用get上unique_ptr<>,但它会自动完成。您必须确保在函数返回后不存储/使用指针(unique_ptr<>在其生命周期结束时将删除它)。
还要确保您不要delete(甚至间接)调用原始指针。
还要确保的另一件事是您没有创建另一个获得指针所有权的智能指针(例如另一个uniqe_ptr<>) - 请参阅上面的删除注释
之所以unique_ptr<>没有做转换为你自动(并有你调用get()明确)是确保你有控制的,当你访问原始指针(避免可能悄无声息,否则发生上述问题)过