C++标准中第15.1.4段规定:
抛出异常时临时副本的内存分配方式未指定,除3.7.3.1中所述外。 只要有处理程序在执行该异常,临时副本就会存在。
我想知道为什么这段代码会崩溃(我知道这不是最佳实践):
class magicException
{
private:
char* m_message;
public:
magicException(const char* message)
{
m_message = new char[strlen(message) + 1];
strcpy(m_message, message);
}
~magicException()
{
cout << "Destructor called." << endl;
delete[] m_message;
}
char* getMessage()
{
return m_message;
}
};
void someFunction()
{
throw magicException("Bang!");
}
int main(int argc, char * argv[])
{
try
{
someFunction();
}
catch (magicException& ex)
{
cout << ex.getMessage() << endl;
}
return 0;
}
具体来说,在 catch 块之前,会调用抛出的 magicException 对象的析构函数。但是,如果我向我的类中添加一个复制构造函数:
magicException(const magicException& other)
{
cout << "Copy constructor called." << endl;
m_message = new char[strlen(other.m_message) + 1];
strcpy(m_message, other.m_message);
}
代码运行良好,析构函数在预期的位置被调用(即catch块的末尾),但有趣的是复制构造函数仍未被调用。它是否被编译器优化掉了(使用关闭优化的Visual C++ 2008编译),还是我漏掉了什么?