Search code examples
c++constructordestructorplacement-newexplicit-destructor-call

Why can't constructors be explicitly called while destructors can?


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);
}

Solution

  • 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.

    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.