std::在 std::shared_ptr 之间交换,<A>其中 A 具有动态数组

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

本文关键字:std 其中 gt 数组 动态 shared 交换 之间 lt ptr      更新时间:2023-10-16

首先,我的代码:

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时,返回值是真实的。

发现Valgrind中的错误: std::enable_if<std::__and_<std::is_move_constructible<A*>, std::is_move_assignable<A*> >::value, void>::type std::swap<A*>(A*&, A*&)

为什么我会遇到此错误?

您显示的不是错误。这是函数声明。

我已经实施了移动操作员

您尚未实施移动分配运算符。


P.S。

  • 您尚未定义移动构造函数。
    • 您已经定义了未声明的构造函数:A::A(TPixel &&)。这可能是相关的。
  • 复制分配运算符
    • 泄漏内存。
    • 将两个对象都指向同一数组。
  • 如果对象被拷贝分配并且副本已经被销毁,则驱动器具有不确定的行为。
相关文章: