简体   繁体   中英

smart pointer - what if constructor throws?

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(...)
{
    //....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM