[英]What is wrong with this usage of the new operator?
Is this allowed? 这是允许的吗?
Object::Object()
{
new (this) Object(0, NULL);
}
Using new(this)
will re-construct member variables. 使用
new(this)
将重构成员变量。 This can result in undefined behavior, since they're not destructed first. 这可能导致未定义的行为,因为它们不会首先被破坏。 The usual pattern is to use a helper function instead:
通常的模式是使用辅助函数:
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) {
/* ... */
}
I believe you want delegate constructors, like Java for example , which are not here yet. 我相信你想要委托构造函数, 例如Java ,它们还没有。 When C++0x comes you could do it like this :
当C ++ 0x出现时你可以这样做:
Object::Object() : Object(0, NULL)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.