c++ - std::move 和 unique_ptr::reset 之间有什么区别?

标签 c++ c++11 unique-ptr

对于std::unique_ptrp1p2std::move()有什么区别> 和 std::unique_ptr::reset()?

p1 = std::move(p2);

p1.reset(p2.release());

最佳答案

根据 [unique.ptr.single.assign]/2 中移动分配的标准规范,答案应该是显而易见的:

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()) 不同因为它做了一些额外的事情。

附加效果很重要,没有它您可能会使用自定义删除器获得未定义的行为:

#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!
}

关于c++ - std::move 和 unique_ptr::reset 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40304840/

相关文章:

c++ - 满足以下条件的高效图算法?

c++ - GDB是否可以只运行一个线程

C++ mysql准备好的语句close和unique_ptr

c++ - 在 C++ 中移动 unique_ptr

c++ - 友元: many classes from same parent

c++ - 如何在 qt4 设计器中创建自定义插槽?

c++ - 替换失败有时是一个错误

c++ - "Downcasting"unique_ptr<Base> 到 unique_ptr<Derived>

c++ - 确保c++中静态变量的构造和销毁顺序

c++ - 继承显式构造函数 (Intel C++)