std::swap between std::shared_ptr<A> where A has dynamic array

std::swap between std::shared_ptr<A> where A has dynamic array

首先,我的代码:

struct A {
  A(int size);
  ~A();

  A(A&& other);
  A& operator=(const A& other);
  uint8_t* data = nullptr;
};

A::A(int size)
{
  data = new uint8_t[size];
}

A::~A()
{
  delete [] data;
  data = nullptr;
}

A::A(TPixel &&other)
{
  data = other.data;
}

A& A::operator=(const A& other)
{
  data = other.data;
}

我有两个变量

std::shared_ptr<A> a = std::make_shared<A>(5);
std::shared_ptr<A> b = std::make_shared<A>(5);

我试过了std::swap(a, b); 并在 valgrind 中发现错误: std::enable_if<std::__and_<std::is_move_constructible<A*>, std::is_move_assignable<A*> >::value, void>::type std::swap<A*>(A*&, A*&)

为什么我会收到这个错误? 我已经实现了移动运算符,当我测试 std::is_move_assignable 和 std::is_move_constructible 时,return 值为真。

found error in valgrind: std::enable_if<std::__and_<std::is_move_constructible<A*>, std::is_move_assignable<A*> >::value, void>::type std::swap<A*>(A*&, A*&)

Why I get this error?

你显示的不是错误。它是一个函数声明。

I have implemented move operators

您尚未实现移动赋值运算符。


P.S.

  • 您还没有定义移动构造函数。
    • 您定义了一个未声明的构造函数:A::A(TPixel &&)。这可能是相关的。
  • 复制赋值运算符
    • 内存泄漏。
    • 使两个对象指向同一个数组。
  • 如果对象已被复制分配并且副本已被销毁,则析构函数具有未定义的行为。