std :: shared_ptr:reset()与分配 [英] std::shared_ptr: reset() vs. assignment

查看:113
本文介绍了std :: shared_ptr:reset()与分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个基本问题,但是我没有找到有关它的先前文章。以下问题的标题听起来可能与我的问题相同,但问题本身与标题不匹配:

This is a basic question, but I did not find a previous post about it. The title of the following question sounds like it might be the same question as mine, but the question itself does not match the title: is it better to use shared_ptr.reset or operator =?

我很困惑 std :: shared_ptr reset()成员函数的目的:除了赋值外,它还有什么作用

I am confused about the purpose of the reset() member function of std::shared_ptr: what does it contribute in addition to the assignment operator?

具体来说,给定定义:

auto p = std::make_shared<int>(1);




  1. 以下两行等效:

  1. Are the following two lines equivalent:

p = std::make_shared<int>(5);
p.reset(new int(5));


  • 这些怎么办:

  • What about these:

    p = nullptr;
    p.reset();
    


  • 如果在两种情况下这两行都相等,那么 reset()的目的是什么?

    If the two lines are equivalent in both cases, then what is the purpose of reset()?

    编辑:让我重新表述这个问题,以更好地强调它的观点。问题是:是否存在 reset()让我们实现没有它就不容易实现的事情?

    Let me re-phrase the question to better emphasize its point. The question is: is there a case where reset() lets us achieve something that is not as easily achievable without it?

    推荐答案

    使用 reset()时,传递给reset的参数不必是托管对象(也不能是)。而对于 = 而言,右侧必须是一个托管对象。

    When using reset() the parameter passed to reset need not be a managed object (nor can it be); whereas with = the right hand side must be a managed object.

    因此,这两行为您提供相同的目的结果:

    So these two lines give you the same end result:

    p = std::make_shared<int>(5); // assign to a newly created shared pointer
    p.reset(new int(5)); // take control of a newly created pointer
    

    但是我们不能这样做:

    p = new int(5); // compiler error no suitable overload
    p.reset(std::make_shared<int>(5).get()); // uh oh undefined behavior
    

    没有 reset()如果不创建共享指针并对其进行分配,就无法将共享指针重新分配给其他原始指针。没有 = ,您将无法使共享指针指向另一个共享指针。

    Without reset() you would not be able to reassign a shared pointer to a different raw pointer without creating a shared pointer and assigning it. Without = you wouldn't be able to make a shared pointer point to another shared pointer.

    这篇关于std :: shared_ptr:reset()与分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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