c++ - 您如何构造一个可能引发异常的对象?

标签 c++ class oop exception error-handling

这将超出范围,因此我无法使用它。

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/

相关文章:

c++ - 从数组创建或 reshape OpenCV 3 channel 垫

php - 从父抽象类调用抽象方法

class - 在 Excel VBA 中使用类处理多个范围

php - 在循环中或不在循环中实例化一个新类?

C#:调用通过另一个抽象类实现的抽象类方法

C++ 在构造函数中通过引用传递

c++ - 编译python3.2 C模块,链接器要求 'python26.lib'

c++ - 隐式转换函数的返回对象时是否会影响性能?

c++ - Lua函数用C++返回字符串

php - 使用 RecursiveDirectoryIterator 将目录和文件列表到数组中?