Search code examples
c++destructorlanguage-designexplicit-destructor-call

Why is the syntax of the destructor ~classname?


The syntax of the destructor is ~classname. This results in the need to explicitly write the type of object in the destructor call. To avoid this, C++17 introduced std::destroy_at.

So, what was Bjarne Stroustrup's original rationale for choosing the ~classname syntax for the destructor? If the syntax does not depend on the types, std::destroy_at is not needed.


Solution

  • Constructors and destructors were a part of C++ from the very earliest days. (They predated the name "C++.") They predated templates as well as the standard container types like vector that templates made possible. In those early days there was little or no allowance for manual construction/destruction as a separate operation from new and delete (e.g. there was no placement-new). Nested classes were also not supported.

    All in all, there was no question of ever needing to refer to the destructor except as part of its definition, and no question that there would be any doubt or complexity in forming the destructor's identifier.

    Naming the constructor after the class fits with C's general tendency for declarations to resemble the usage of the things they declare (e.g. int *a(int b) results in something where *a(b) is well-formed). The destructor is conceptually linked to the constructor, so it would be weird for the class name to show up in the constructor but not the destructor. And with no support for operator overloading (at the time) beyond operator=, there was no question of confusing ~classname with an overloaded operator~. So it was a simple, low-stakes, mildly witty syntax detail.