Why the Destructor in C++ de-allocated memory in reverse order of how they were initialised?

前端 未结 3 1316
日久生厌
日久生厌 2021-02-13 03:12

What is the advantage in de-allocating memory in reverse order to variables?

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-13 04:02

    It's not just about deallocating memory, it's about symmetry in a broader sense.

    Each time you create an object you are creating a new context to work in. You "push" into these contexts as you need them and "pop" back again later -- symmetry is necessary.

    It's a very powerful way of thinking when it comes to RAII and exception-safety, or proving correctness w.r.t. preconditions and postconditions (constructors establish invariants, destructors ought to assert() them, and in well-designed classes each method clearly preserves them).

    IMHO, lack of this feature is Java's single biggest flaw. Consider objects whose constructors open file handles or mutexes or whatever -- Armen's answer brilliantly illustrates how this symmetry enforces some common-sense constraints (languages such as Java may let Object1 go out of scope before Object2 but Object2 keeps Object1 alive by reference counting) but there's a whole wealth of design issues that fall neatly into place when considered in terms of object lifetimes.

    Lots of C++ gotchas explain themselves when you bear this in mind

    • why gotos can't cross initialisations
    • why you may be advised to have only one return in any function (this only applies to non-RAII languages such as C and Java)
    • why an exception is the only reasonable way for a constructor to fail, and likewise why destructors can never reasonably throw
    • why you shouldn't call virtual functions in a constructor

    etc etc...

提交回复
热议问题