这将超出范围,所以我不能使用它。
try
{
SomeClass someObject({});
}
catch (std::exception & e)
{
}
someObject(x); // someObject does not exist because it goes out of scope
这里有一个有用的应用 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安全。
动态地构造对象,例如::
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...
}