Is the destructor called if the constructor throws an exception?

前端 未结 8 984
不知归路
不知归路 2020-11-29 06:57

Looking for an answer for C# and C++. (in C#, replace \'destructor\' with \'finalizer\')

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 07:54

    In C++, the answer is no - object's destructor is not called.

    However, the destructors of any member data on the object will be called, unless the exception was thrown while constructing one of them.

    Member data in C++ is initialized (i.e. constructed) in the same order as it is declared, so when the constructor throws, all member data that has been initialized - either explicitly in the Member Initialization List (MIL) or otherwise - will be torn down again in reverse order.

提交回复
热议问题