为什么shared_ptr不允许直接分配 [英] Why doesn't shared_ptr permit direct assignment

查看:74
本文介绍了为什么shared_ptr不允许直接分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当使用 shared_ptr< Type> 时,您可以这样写:

So when using shared_ptr<Type> you can write:

shared_ptr<Type> var(new Type());

我想知道为什么他们不允许更简单更好的(imo):

I wonder why they didn't allow a much simpler and better (imo):

shared_ptr<Type> var = new Type();

要实现此功能,您需要使用 .reset()

Instead to achieve such functionality you need to use .reset():

shared_ptr<Type> var;
var.reset(new Type());

我习惯于OpenCV Ptr类,该类是一个智能指针,允许直接分配并且一切正常/ p>

I am used to OpenCV Ptr class that is a smart pointer that allows direct assignment and everything works fine

推荐答案

允许将原始指针隐式转换为 std :: shared_ptr 的问题c $ c>可以用

The issue with allowing a raw pointer to be implicitly converted into a std::shared_ptr can be demonstrated with

void foo(std::shared_ptr<int> bar) { /*do something, doesn't matter what*/ }

int main()
{
    int * bar = new int(10);
    foo(bar);
    std::cout << *bar;
}

现在,如果隐式转换对内存 bar 指向的指针将在 foo()的末尾由 shared_ptr 析构函数删除。当我们在 std :: cout<<中访问它时* bar; 在取消引用已删除的指针时,我们现在具有未定义的行为。

Now if the implicit conversion worked the memory bar points to would be deleted by the shared_ptr destructor at the end of the foo(). When we go to access it in std::cout << *bar; we now have undefined behavior as we are dereferencing a deleted pointer.

在您的情况下,您直接在呼叫站点创建指针因此没关系,但是从示例中可以看出,它可能会导致问题。

In your case you create the pointer directly at the call site so it does not matter but as you can see from the example it can cause problems.

这篇关于为什么shared_ptr不允许直接分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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