如何构造一个可以抛出异常的对象?

问题描述 投票:0回答:1

这将超出范围,所以我不能使用它。

try
{
    SomeClass someObject({});
}
catch (std::exception & e)
{

}

someObject(x); // someObject does not exist because it goes out of scope
c++ class oop exception error-handling
1个回答
2
投票

这里有一个有用的应用 std::optional.

std::optional<SomeClass> maybe_someobject;

try {
     maybe_someobject.emplace( /* Constructor parameters go here */);
} catch (...  /* or something specific */)
{
     /* catch exceptions */
     return; // Do not pass "Go". Do not collect $200.
}

SomeClass &someobject=maybe_someobject.value();

// Use someobject normally, at this point. Existing code will have to look
// very hard to be able to tell the difference.

这增加了一点开销,但它是相当小的,但你保留了完整的类型和RAII安全。


1
投票

动态地构造对象,例如::

SomeClass *someObject = nullptr;

try
{
    someObject = new SomeClass(...);
}
catch (const std::exception &e)
{

}

// or:
// SomeClass *someObject = new(nothrow) SomeClass(...);

if (someObject)
{
    // use someObject as needed...
    delete someObject;
}

或者:

std::unique_ptr<SomeClass> someObject;

try
{
    someObject.reset(new SomeClass(...));
    // or:
    // someObject = std::make_unique<SomeClass>(...);
}
catch (const std::exception &e)
{

}

if (someObject)
{
    // use someObject as needed...
}
© www.soinside.com 2019 - 2024. All rights reserved.