Order and point of calling destructor

倾然丶 夕夏残阳落幕 提交于 2019-11-28 01:56:44

// m1 and m2 will get unlocked here. But in what order? m1 first or m2 first?

The destructors will be called in the reverse order of construction: m2 then m1.

In that case is it important to be explicit rather than relying on destructors?

The order of destruction is well-specified so that you can rely on it.

Also, can destruction be delayed by the compiler in any case?

No. If it did, that would break a lot of RAII-based code (your MutexLock class is a very good example of that).

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.

The destruction happens in reverse order of construction: first m2 then m1.

Compiler can never delay object's lifetime behind scope end (}).

The object is always destroyed when it goes out of scope - this is not java. f Will get destroyed where you indicate and will never be destroyed at the end of func. in general the destructors are called in order reverse to the order of their construction.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!