为什么不能在析构函数可以的同时显式调用构造函数? [英] Why can't constructors be explicitly called while destructors can?
问题描述
在下面的C ++代码中,允许我显式调用析构函数,但不能显式调用构造函数.这是为什么?不会在dtor案件中明确要求更富有表现力和统一吗?
In the following C++ code, I am allowed to explicitly call the destructor but not the constructor. Why is that? Wouldn't be explicit ctor call more expressive and unified with the dtor case?
class X { };
int main() {
X* x = (X*)::operator new(sizeof(X));
new (x) X; // option #1: OK
x->X(); // option #2: ERROR
x->~X();
::operator delete(x);
}
推荐答案
由于在构造函数启动之前,该地址处没有 X
类型的对象.因此,将 x
取消引用为 X
类型或访问其成员/方法将是未定义行为.
Because before the constructor is started, there is no object of type X
at that address. As such, dereferencing x
as an X
type or accessing members/methods of it would be Undefined Behavior.
所以 x-> X();
(假设语法)和 x->〜X()
之间的主要区别是在第二种情况下有一个可以调用(特殊)成员(例如析构函数)的对象,而在第一种情况下,尚无对象,可以在其上调用方法(甚至是特殊方法-构造函数)
So the major difference between x->X();
(hypothetical syntax) and x->~X()
is that in the 2nd case you have an object on which you can call a (special) member such as the destructor, while in the first case, there is no object yet on which you can call methods (even the special method - constructor).
您可能会争辩说此规则可能会有例外,但是最终这将是语法偏爱的问题,在这两种情况下您都不一致.使用当前语法,对构造函数的调用看起来不像对构造函数的调用,在您建议的语法中,析构函数的调用是对称的,但是控制何时可以取消引用/访问对象方法的规则不一致.实际上,必须有一个例外,允许在尚未成为对象的对象上调用方法.然后,您必须在标准字母中严格定义还不是对象的东西.
You could argue that there could be an exception to this rule, but then it ultimately would be a matter of syntax preference, where you have inconsistencies in both cases. With the current syntax the call to constructor doesn't look like a call to constructor, in your proposed syntax there would be symmetry with the destructor call, but inconsistencies in the rules which govern when you can dereference/access methods of an object. Actually there would have to be an exception allowing calling a method on something that is not a object yet. Then you would have to strictly define in the letter of the standard something that is not an object yet.
这篇关于为什么不能在析构函数可以的同时显式调用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!