Search code examples
c++c++11stdmove

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


first, my code:

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;
}

I have two variable

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

I tried std::swap(a, b); and 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 and when I tested std::is_move_assignable and std::is_move_constructible the return value was true.


Solution

  • 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?

    What you show is not an error. It is a function declaration.

    I have implemented move operators

    You have not implemented a move assignment operator.


    P.S.

    • You haven't defined the move constructor.
      • You have defined a constructor that you didn't declare: A::A(TPixel &&). This may be related.
    • The copy assignment operator
      • leaks memory.
      • leaves both objects pointing to the same array.
    • The destructor has undefined behaviour if the object has been copy-assigned and the copy has already been destroyed.