| ▲ | quietbritishjim a day ago | |
There's really two things in play here. One is that C++ has constructors, with lots of rules about which one is called when. But the other is that primitive objects can sometimes be uninitialised, and sometimes that's what you want for performance (if you're about to overwrite them anyway). C++ classes are meant to be able to do anything a primitive type can (as a sibling comment says) so you sometimes want a class that you can either leave uninitialised or value initialise (essentially, set everything to zero) decided at the call site (not in the class declaration). If C++ guaranteed that all members always had to be initialised, then all the default-like constructors (Foo x; Foo x = {}; Foo x = Foo(); etc) would resolve to the same thing (a call to the constructor you explicitly wrote if you did; otherwise all members default constructed, resolved as zero-initialisation if that's equivalent). | ||
| ▲ | Joker_vD a day ago | parent [-] | |
First of all, there is a question of syntax, which ironically could be solved by taking a page out of BCPL's book (the irony is that BCPL is C's ancestor, but C lost several of its more advanced features, like statement expressions):
Second, there is a question of semantics. You only get to have 1 destructor, and it's called unconditionally — so we force the author of Foo (or of any class, really) to either 1) write the destructor that can properly destruct an unitialized object which is a bit tricky since reading any of the fields of such an object is UB; 2) shift the blame to the users: "don't do that with this class" — which completely negates your "decided at the call site (not in the class declaration)" point, because this decision is made in the class declaration, and can be made only there, not at the call site.So as usual with C++, we end up with a half-working system, with subtle footguns, pervading all of the program code, and impossible to ignore. | ||