什么是std :: move和unique_ptr :: reset之间的区别? [英] what are the differences between std::move and unique_ptr::reset?

查看:2363
本文介绍了什么是std :: move和unique_ptr :: reset之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: unique_ptr s p1 p2 std :: move() std :: unique_ptr :: reset()? / p>

For std::unique_ptrs p1 and p2, what are differences between std::move() and std::unique_ptr::reset()?

p1 = std::move(p2);

p1.reset(p2.release());


推荐答案

分配给[unique.ptr.single.assign] / 2:

The answer should be obvious from the standard's specification of move assignment in [unique.ptr.single.assign]/2:


效果:如果通过调用 reset(u.release()),则 u $ c>后面是 std :: forward< D>(u.get_deleter())的分配。

Effects: Transfers ownership from u to *this as if by calling reset(u.release()) followed by an assignment from std::forward<D>(u.get_deleter()).

清除移动赋值不等于 reset(u.release()),因为它有额外的功能。

Clearly move assignment is not the same as reset(u.release()) because it does something additional.

额外的效果很重要,没有它你可以得到未定义的行为与自定义删除:

The additional effect is important, without it you can get undefined behaviour with custom deleters:

#include <cstdlib>
#include <memory>

struct deleter
{
  bool use_free;
  template<typename T>
    void operator()(T* p) const
    {
      if (use_free)
      {
        p->~T();
        std::free(p);
      }
      else
        delete p;
    }
};

int main()
{
  std::unique_ptr<int, deleter> p1((int*)std::malloc(sizeof(int)), deleter{true});
  std::unique_ptr<int, deleter> p2;
  std::unique_ptr<int, deleter> p3;

  p2 = std::move(p1);  // OK

  p3.reset(p2.release());  // UNDEFINED BEHAVIOUR!
}

这篇关于什么是std :: move和unique_ptr :: reset之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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