Ign*_*cia 2 c++ memory-management
我有这样的事情:
void Test(void)
{
char errorMessage[256];
spintf(errorMessage,... blablabla);
throw new CustomException(errorMessage);
}
Run Code Online (Sandbox Code Playgroud)
这会是内存泄漏,因为errorMessage不会被释放吗?或者这会在try {} catch中访问异常消息时导致异常,因为在从函数中退出时已释放errorMessage?
提前致谢.
errorMessage当catch处理程序访问时,已经释放了内存.但是,您可以将其复制到std::stringin CustomException的构造函数中.
另一方面,内存泄漏可能是由异常本身引起的,因为您将它放在堆上.这不是必需的.
小智 7
答案是肯定的,非常可能.你永远不应该抛出用它创建的对象new.相反,抛出值:
throw CustomException(errorMessage);
Run Code Online (Sandbox Code Playgroud)
并使用const引用捕获:
try {
...
}
catch( const CustomException & e ) {
...
}
Run Code Online (Sandbox Code Playgroud)
抛出值意味着编译器处理抛出对象的生命周期.此外,在您的代码中,如果异常类的复制构造函数不正确,您可能会遇到另一个问题 - 但这与异常处理没有任何关系.