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