这是允许的吗?
Object::Object()
{
new (this) Object(0, NULL);
}
Run Code Online (Sandbox Code Playgroud)
使用new(this)将重构成员变量.这可能导致未定义的行为,因为它们不会首先被破坏.通常的模式是使用辅助函数:
class Object {
private:
void init(int, char *);
public:
Object();
Object(int, char *);
};
Object::Object() {
init(0, NULL);
}
Object::Object(int x, char *y) {
init(x, y);
}
void Object::init(int x, char *y) {
/* ... */
}
Run Code Online (Sandbox Code Playgroud)