Ped*_*ios 0 c++ copy copy-assignment
我必须用来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)
将自定义类复制到未初始化的内存是否安全?
谢谢
Placement new是正确的
使用A& operator=(const A& other)非构造的" this"是不正确的(想象一下,如果你有一个非平凡的类型,因为std::string在A做法中应该在影响新值之前销毁一个未初始化的字符串).
放置新内容后,您可以使用分配.
auto p = new (a) A;
*p = b; // ok
Run Code Online (Sandbox Code Playgroud)