![]() ![]() This means that in practice, it's not really a big deal. However, components of the object which have already successfully constructed are already the compilers responsibility. If an exception throw occurs inside the constructor, anything part-constructed needs to be explicitly cleaned up, typically in a try. This is known as RAII (Resource Allocation Is Initialization) which isn't really the best name. Therefore, the responsibility for destructing the object only transfers to the compiler when the constructor successfully completes. While you're still in a constructor call, the object isn't necessarily fully constructed, so it's not valid to call the destructor for that object. ![]() Basically, there has to be a well-defined point when the compiler becomes responsible for calling destructors. The reasons relate to automatic destructor cleanup, particularly in the face of exceptions. However, there are reasons behind the style rule, and there's ways to have both minimal constructors and strong invariants. In particular, as my sarcasm indicates, I'm in the camp that says weakening invariants is almost always too high a price. Ahem.Īlthough common, certainly in this extreme form it's very far from absolute. For example if allocating storage for your class to manage is too expensive, add a not-allocated-yet null state, because of course having special-case states like null never caused anyone any problems. If there's no cheap-to-initialize value that your constructor can set up, you should weaken the invarants enforced by your class to add one. If your initialization is more complex, it should be handled outside the constructor. It's a common style rule that constructors should do the absolute minimum they can to set up a defined valid state. The style rule persists anyway, but normally that's not a problem - not all initialization has to be in the constructor, and particularly not necessarily that constructor. Handling of exceptions in constructors is well defined, and destructors will still be called for fully-constructed local variables and members, which means there shouldn't be any problems in idiomatic C++ code. ![]() TL DR = there's a style rule to keep constructors simple, there's reasons for it, but those reasons mostly relate to a historic (or simply bad) style of coding. Already gave the simple, direct answers, but some extra explanation might be useful. ![]()
0 Comments
Leave a Reply. |