문제

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.

도움이 되었습니까?

해결책

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(...)
{
    //....
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top