Search code examples
c++copycopy-assignment

Is it safe to copy a class into uninitialized memory?


I have to use malloc to allocate memory. I have a custom class that needs a custom operator=. Let's say it is A:

class A {
public:
  int n;
  A(int n) : n(n) {}
  A& operator=(const A& other) {
   n = other.n;
   return *this;
  }
};

I allocate memory with malloc:

int main() {
   A* a = (A*) malloc(sizeof(A));
   A b(1);

   //Is it safe to do this as long as I copy everything in operator=?
   *a = b;

   //Clean up
   a->~A();
   free(a);
   return 0;
}

I know I can also use placement new:

a = new (a) A(b);

Is it safe to copy a custom class to uninitialized memory?

Thanks


Solution

  • Placement new is correct

    using A& operator=(const A& other) with a non constructed "this" is incorrect (imagine if you have a non trivial type as std::string inside A the affectation should destroy a non initialized string before affecting the new value).

    Once you have do placement new, you can use assignment.

    auto p = new (a) A;
    *p = b; // ok