我有這樣的代碼..手動拋出std :: bad_alloc可以嗎?
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的構造函數拋出。 – 2010-12-05 12:00:59
我編輯了視頻圖層部分,因爲我實際上沒有視頻圖層,但想要顯示我的問題。我決定簡單而不是準確。 – Jookia 2010-12-05 13:30:03