在unique_ptr上使用强制转换运算符有危险吗? [英] Is it dangerous to have a cast operator on a unique_ptr?

查看:44
本文介绍了在unique_ptr上使用强制转换运算符有危险吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We have an extensive code base which currently uses raw pointers, and I'm hoping to migrate to unique_ptr. However, many functions expect raw pointers as parameters and a unique_ptr cannot be used in these cases. I realize I can use the get() method to pass the raw pointer, but this increases the number of lines of code I have to touch, and I find it a tad unsightly. I've rolled my own unique_ptr which looks like this:

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

    operator T*() { return get(); };
};

然后,每次我向需要原始指针的函数parm提供my_unique_ptr时,它就会自动将其转换为原始指针.

Then every time I provide a my_unique_ptr to a function parm which expects a raw pointer, it automagically turns it into the raw pointer.

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

Question: Is there something inherently dangerous about doing this? I would have thought this would have been part of the unique_ptr implementation, so I'm presuming its omission is deliberate - does anyone know why?

推荐答案

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

There's a lot of ugly things that can happen on accident with implicit conversions, such as this:

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.
}

这篇关于在unique_ptr上使用强制转换运算符有危险吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆