这将超出范围,因此我无法使用它。
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安全性。
关于c++ - 您如何构造一个可能引发异常的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61397765/