std::shared_ptr: reset() vs. assignment

后端 未结 4 1374
小鲜肉
小鲜肉 2021-02-04 23:58

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 it

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-05 00:34

    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(5); // assign to a newly created shared pointer
    p.reset(new int(5)); // take control of a newly created pointer
    

    But we cannot do:

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

    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.

提交回复
热议问题