samedi 30 septembre 2017

c++11 move constructor and move assigment usage

I try to figure out when move constructor and move assignment constructor is used, my code is:

class A {
 public:
  A(int p) {
    printf("constructor\n");
    ptr = new int(p);
  }
  ~A() {
    delete ptr;
    ptr = nullptr;
  }
  A(const A& a) {
    if (ptr == a.ptr) {
      return;
    } else {
      delete ptr;
      ptr = a.ptr;
    }
  }

  A(A&& a) {
    printf("move constructor\n");
    if (ptr == a.ptr) {
      a.ptr = nullptr;
      return;
    } else {
      ptr = a.ptr;
      a.ptr = nullptr;
    }
  }
  A& operator=(A&& a) {
    printf("move assign constructor\n");
    if (ptr == a.ptr) {
      a.ptr = nullptr;
      return *this;
    } else {
      ptr = a.ptr;
      a.ptr = nullptr;
    }
    return *this;
  }

  void print() {
    if (ptr) {
      printf("value = %d\n", *ptr);
    } else {
      printf("empty value\n");
    }
  }

 private:
  int* ptr;
};

this is my simple class support move operate. and I use a function to test it:

void f(A&& a) {
  printf("f begin------->\n");
  A al = std::move(a);
  printf("f end------->\n");
}

int main () {
  A a1(1);
  f(std::move(a1));
  a1.print();

  return 0;
}

the out put is OK:

constructor
f begin------->
move constructor
f end------->
empty value

but if I try to use move assignment by change f() like this:

void f(A&& a) {
  printf("f begin------->\n");
  A al = a;
  printf("f end------->\n");
}

Oops:

constructor
f begin------->
*** Error in `./test': free(): invalid pointer: 0x00007ffd64fb7280 ***
Aborted

It is supposed to use move assignment, but fail with a invalid pointer. That is why?

Aucun commentaire:

Enregistrer un commentaire