【发布时间】:2011-05-20 10:52:55
【问题描述】:
我有这个代码..
CEngineLayer::CEngineLayer(void)
{
// Incoming creation of layers. Wrapping all of this in a try/catch block is
// not helpful if logging of errors will happen.
logger = new (std::nothrow) CLogger(this);
if(logger == 0)
{
std::bad_alloc exception;
throw exception;
}
videoLayer = new (std::nothrow) CVideoLayer(this);
if(videoLayer == 0)
{
logger->log("Unable to create the video layer!");
std::bad_alloc exception;
throw exception;
}
}
IEngineLayer* createEngineLayer(void)
{
// Using std::nothrow would be a bad idea here as catching things thrown
// from the constructor is needed.
try
{
CEngineLayer* newLayer = new CEngineLayer;
return (IEngineLayer*)newLayer;
}
catch(std::bad_alloc& exception)
{
// Couldn't allocate enough memory for the engine layer.
return 0;
}
}
我已经省略了大部分不相关的信息,但我认为这里的图片很清楚。
是否可以手动抛出 std::bad_alloc 而不是单独尝试/捕获所有层创建并在重新抛出 bad_allocs 之前记录?
【问题讨论】:
-
一个小提示,如果你没有为记录器使用智能指针,那么如果 CVideoLayer 的构造函数抛出,这将泄漏。
-
我编辑了视频层部分,因为我实际上还没有视频层,并且想展示我的问题。我决定让它简单而不是准确。
标签: c++ new-operator throw bad-alloc