c++的構造函數中會發生異常處理的情況,這時候其不會跳轉到析構函數了,該異常需要自己來處理。
#include <iostream>
class TestA
{
public:
TestA()
{
//基類中異常
try
{
std::cout << "TestA Contructor" << std::endl;
throw std::string("testA exception");
}
catch (const std::string& exp)
{
//std::cout << exp.c_str() << std::endl;
throw;
}
}
~TestA()
{
std::cout << "TestA Destructor" << std::endl;
}
};
class TestB
{
public:
TestB()
{
std::cout << "TestB Constructor" << std::endl;
}
~TestB()
{
std::cout << "TestB Destructor" << std::endl;
}
};
class TestC
{
public:
TestC()
{
//異常
try
{
m_a = new TestA();
m_b = new TestB();
throw std::string("something trigger a exception");
}
catch (const std::string& exp)
{
std::cout << exp.c_str() << std::endl;
Reset();
throw;
}
std::cout << "TestC() Constructor" << std::endl;
}
~TestC()
{
Reset();
std::cout << "TestC() Destructor" << std::endl;
}
void Reset()
{
if (m_a != nullptr)
{
delete m_a;
m_a = nullptr;
}
if (m_b != nullptr)
{
delete m_b;
m_b = nullptr;
}
}
private:
TestA* m_a;
TestB* m_b;
};
int main()
{
try
{
TestC tc;
}
catch (...)
{
std::cout<<"constructor fail"<< std::endl;
}
}