Order and point of calling destructor

后端 未结 4 910
盖世英雄少女心
盖世英雄少女心 2020-12-07 01:42

Lets say I have two local objects. When the function returns, is it guaranteed which one will go out of the scope first?

For example:

I have a class like thi

4条回答
  •  日久生厌
    2020-12-07 02:26

    In that case is it important to be explicit rather than relying on destructors?
    No, it is not required.
    The order of destruction of objects in a scope is well defined.
    It is exact opposite of the order in which they were constructed.


    Also, can destruction be delayed by the compiler in any case?
    No.
    The compiler cannot and that is the purpose of RAII. It provides the mechanism to implicitly clean & deallocate resources without any explicit manual effort on part of the programmer.
    Your requirement of delaying the destruction is parallel to the very purpose of RAII, it calls for manual resource management.
    If you need manual resource management you can have pointers allocated on heap through newand the objects pointed by them would be valid unless and until, you explicitly deallocate them through delete call and the order in which you call them.
    Of-course, it is nor advisable nor encouraged to do so.

提交回复
热议问题