Frage

I have a class that connects to a USB device in the constructor. If the device isn't present or some other situation fails then the constructor throws an exception and the calling code deals with it.

Something akin to:

CDevice* pDevice = NULL;
try
{
    pDevice = new CDevice();
}

and so on. I would like to replace this call with an auto_ptr but am not clear how to trap the exception while maintaining the correct scope of the object.

War es hilfreich?

Lösung

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(...)
{
    //....
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top