First, I recommend you don't use auto_ptr
, it's somewhat broken and has been deprecated in C++11. Prefer either Boost or C++11 SBRM classes like std::unique_ptr
. You can do this without much modification to your example.
std::unique_ptr<CDevice> pDevice;
try
{
pDevice.reset(new CDevice());
}
catch(...)
{
//....
}
If new
or the constructor of CDevice
throws then pDevice will remain empty. Using auto_ptr
isn't much different, just not recommended given the available alternatives.
std::auto_ptr<CDevice> pDevice;
try
{
pDevice.reset(new CDevice());
//pDevice = std::auto_ptr<CDevice>(new CDevice());
// ^^ historical masochism.
}
catch(...)
{
//....
}