Is the destructor called if the constructor throws an exception?

前端 未结 8 935
不知归路
不知归路 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.

    0 讨论(0)
  • 2020-11-29 07:56

    For C++ this is addressed in a previous question: Will the below code cause memory leak in c++

    Since in C++ when an exception is thrown in a constructor the destructor does not get called, but dtors for the object's members (that have been constructed) do get called, this is a primary reason to use smart pointer objects over raw pointers - they are a good way to prevent memory leaks in a situation like this.

    0 讨论(0)
提交回复
热议问题