DISQUS

Reflections of my thoughts: You Should Avoid Partial Initialization of Objects

  • Dilip · 2 years ago
    You seem to be advocating some strange rules. Throwing exception from a constructor is a well established way of informing the client code that the object construction did not take place due to some fatal error. In fact it is the only way the caller can ever know if an object was constructed properly.

    Now, whether allocated memory in ctors gets freed properly (before the exception is thrown) is another issue altogether. That part is well covered by Scott Meyers in his More Effective C++.

    The only agreeable point is you SHOULD NOT throw exceptions from a destructor because the dtor might be executing as a part of stack-unwind caused by another live exception. The implementation will just call atexit or something like that and abort the application in such scenarios.
  • S a r a t h · 2 years ago
    Dear Dilip,
    In Item 12(Copy all parts of an object ) of effective C++ 3rd Edition it is saying copy all part of an object in copy constructor or operator =. I think it is also applicatioble in the case of construction. i.e initialize all parts of an object. Sorry I was not creating new rules but I was posting an incident which can cause some unexpected behavior.
    IMHO partial initialization of objects are not good. I reffered the name effective C++ because that many people may seem that this is an copied post. that's why I mentioned that name.

    You are said about destructor is true but IMO, you should INTIIALIZE ALL PART OF AN OBJECT. I know the code I posted is a foolish one but still people making mistakes.
  • cpon · 2 years ago
    There is more information about why not throwing exception in constructors and destructors. http://kal-el.ugr.es/~jmerelo/c++-faq/exception...