0

I'm studying C++ and read the following:

When an object is destroyed, its destructor first executes the destructor's body, and then >calls the destructors of all of the members. Member destructors are called in reverse order of creation

But why is this correct? the programmer is the one who writes the destructor, so he could write it in any order he wants to which probably may be different than what is mentioned above.

  • *so he could write it in any order he wants* -- Sorry, but no. – PaulMcKenzie May 11 '20 at 02:09
  • 1
    This is required by the C++ standard. This is because objects that get constructed later can reference objects that were already constructed, and can expect the previously constructed objects to exist as long as the later-constructed objects exist. Therefore the order of destruction must be in reverse of the order of construction. See the linked question for more information. – Sam Varshavchik May 11 '20 at 02:09
  • so I will get an error? –  May 11 '20 at 02:12
  • @clark_smith1 You can't get an error since there is no way to control the order of destruction. If your code has bad side-effects that occur due to the order of destruction, then you should fix your code. – PaulMcKenzie May 11 '20 at 02:21
  • I'm a little bit confused, please tell me which is right: a) I can write the *order* of lines of the destruction function but the compiler will rearrange them as he sees is right. b) the order is unique and I MUST write one fixed order. –  May 11 '20 at 02:25
  • *"the programmer is the one who writes the destructor,"* -- not quite, given your confusion. The programmer is the one who writes the destructor's body. After that is run, the compiler calls the destructors as described in your quote. – JaMiT May 11 '20 at 02:35
  • so 'a' is right? –  May 11 '20 at 02:46
  • @clark_smith1 No, the compiler will not rearrange the lines in the body of the destructor (no more than it rearranges lines of code in other function bodies). – JaMiT May 11 '20 at 04:29
  • @clark_smith1 To be more direct, neither 'a' nor 'b' is correct. The quote says nothing about the order of lines written by the programmer. – JaMiT May 11 '20 at 22:47

0 Answers0