2

I know that when a constructor fails, the completed member objects will be destroyed. There is no memory leak.

My question is that how does compiler do that? How can compiler know what member is constructed? Does it make any record of it? Does the compiler really destroy everything in this case? How does it guarantee this?

2
  • 1
    See stackoverflow.com/questions/188693/…. Commented Mar 3, 2010 at 15:09
  • Is it really that much different from cleaning up function-local variables (including in case of early returns and exceptions)? Why do you need to know? Commented Mar 3, 2010 at 15:31

1 Answer 1

4

How the compiler does that is up to the compiler.

But yes, you are guaranteed that any constructed objects will be destructed (in the reverse order they were constructed). §15.2/2:

An object that is partially constructed or partially destroyed will have destructors executed for all of its fully constructed subobjects, that is, for subobjects for which the constructor has completed execution and the destructor has not yet begun execution. Should a constructor for an element of an automatic array throw an exception, only the constructed elements of that array will be destroyed. If the object or array was allocated in a new-expression, the matching deallocation function (3.7.3.2, 5.3.4, 12.5), if any, is called to free the storage occupied by the object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.