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

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

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

3条回答
  •  天命终不由人
    2021-02-13 04:03

    Consider this example:

    Type1 Object1;
    Type2 Object2(Object1);
    

    Suppose that Object2 uses some internal resources of Object1 and is valid as long as Object1 is valid. For example, Object2s destructor accesses Object1's internal resource. If it weren't for the guarantee of reverse order of destruction, this would lead to problems.

提交回复
热议问题