2

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.

4

1 に答える 1

6

まず、 を使用しないことをお勧めします。これはauto_ptrやや壊れており、C++11 では非推奨になっています。Boost または のような C++11 SBRM クラスのいずれかを優先しますstd::unique_ptr。例をあまり変更せずにこれを行うことができます。

std::unique_ptr<CDevice> pDevice;
try
{
    pDevice.reset(new CDevice());
}
catch(...)
{
    //....
}

newまたは throws のコンストラクターの場合CDevice、pDevice は空のままになります。使用auto_ptr方法に大きな違いはありませんが、利用可能な代替手段を考えると推奨されません。

std::auto_ptr<CDevice> pDevice;

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

    //pDevice = std::auto_ptr<CDevice>(new CDevice());
    // ^^ historical masochism. 
}
catch(...)
{
    //....
}
于 2013-04-18T20:07:54.647 に答える