1

There are already several questions about this on StackOverflow but none of them adequately capture the nature of throwing exceptions from constructors and the memory implication of doing such in certain cases.

What I'd like to ask is about the memory safety of throwing an exception during construction, assuming we have several allocation objects in construction.

From what I understand (what we've been taught) is that if an exception is thrown from the constructor, then the destructor doesn't have a guarantee to be called, so the object could be left in an inconsistent state. Not sure if I interpreted that correctly.

So if we have objects such as vectors of deques in a more complex constructor (assuming we aren't using an Init() method so we don't violate RAII), could this mean their memory doesn't get released?.. Or do they get destructed because they're in the scope of the constructor?..

Another point of view is if we have a deque as a private variable of the class, and we add items to it during construction, which then fails. Since this deque was made during initialization, does it mean it won't get destructed / released when an exception is thrown during object construction, leading to a potential leak?

This is all assuming we're not using a separate class to encapsulate our throwing class, to catch exceptions and handle them alone.

What is the safest way to throw an exception during construction, taking all of this in mind? Should we manually call the destructor before throwing, in case we have manual memory allocations and whatnot?

Jack Avante
  • 1,405
  • 1
  • 15
  • 32
  • Does this help? https://stackoverflow.com/questions/10212842/what-destructors-are-run-when-the-constructor-throws-an-exception – parktomatomi Nov 05 '20 at 10:19
  • Somewhat yes, but it still doesn't clear up the fact what would happen with an object such a deque if we pushed items into it during construction, which then didn't finish. It has to have been constructed or objects wouldn't be pushable into it, so from what I understand, it doesn't get freed – Jack Avante Nov 05 '20 at 11:11
  • First, if you throw an exception from a constructor, there is no object, so it doesn't mean anything to talk about the object's state. Second, all sub-objects that have been constructed at the point where the exception is thrown will be destroyed. That's required by the language definition, and it's up to compilers to get it right. – Pete Becker Nov 05 '20 at 13:08
  • Then, in which case do we have to worry about the destructor not being called since it doesn't if an exception is thrown? – Jack Avante Nov 05 '20 at 13:59
  • @JackAvante: Certainly side effects (*e.g.*, adding to an *existing* container) are not rewound automatically. Use scope guards to deal with that, or just avoid such side effects in constructors (which should generally avoid affecting *other* objects). – Davis Herring Nov 05 '20 at 15:20

0 Answers0