我必须用来malloc分配内存.我有一个需要自定义的自定义类operator=.让我们说它是A:
class A {
public:
int n;
A(int n) : n(n) {}
A& operator=(const A& other) {
n = other.n;
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
我分配内存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;
}
Run Code Online (Sandbox Code Playgroud)
我知道我也可以使用新的位置:
a = new (a) A(b);
Run Code Online (Sandbox Code Playgroud)
将自定义类复制到未初始化的内存是否安全?
谢谢