简体   繁体   English

智能指针-如果构造函数抛出该怎么办?

[英]smart pointer - what if constructor throws?

I have a class that connects to a USB device in the constructor. 我有一个连接到构造函数中的USB设备的类。 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. 我想用auto_ptr代替此调用,但不清楚如何在保持对象正确范围的同时捕获异常。

First, I recommend you don't use auto_ptr , it's somewhat broken and has been deprecated in C++11. 首先,我建议您不要使用auto_ptr ,它有些破损,在C ++ 11中已弃用。 Prefer either Boost or C++11 SBRM classes like std::unique_ptr . 最好使用Boost或C ++ 11 SBRM类,例如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. 如果newCDevice的构造函数抛出,则pDevice将保持为空。 Using auto_ptr isn't much different, just not recommended given the available alternatives. 使用auto_ptr并没有太大区别,只是在给定可用替代方法的情况下不建议这样做。

std::auto_ptr<CDevice> pDevice;

try
{
    pDevice.reset(new CDevice());

    //pDevice = std::auto_ptr<CDevice>(new CDevice());
    // ^^ historical masochism. 
}
catch(...)
{
    //....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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