【问题标题】:How do you construct an object that can throw exception?你如何构造一个可以抛出异常的对象?
【发布时间】:2020-08-07 09:36:49
【问题描述】:

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

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

}

someObject(x); // someObject does not exist because it goes out of scope

【问题讨论】:

  • 将用法移到 try 语句块中
  • .......但是......但是......可能需要数百行代码进入那里。那不是很糟糕吗?编辑:好吧,也许是 10 行...
  • 把它想象成“我正在用 try {} 包装现有的行”
  • pfft 耸耸肩 好吧!我会同意的。
  • 如果默认构造函数是noexcept,并且有一个,当然可以在try块外定义变量,然后在try块内复制赋值。但是,如果施工失败,您真的要继续吗?

标签: c++ class oop exception error-handling


【解决方案1】:

这是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 安全性。

【讨论】:

    【解决方案2】:

    动态构造对象,例如:

    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...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 2011-08-20
      • 2017-12-04
      • 2011-06-25
      • 2021-10-31
      • 2011-08-04
      • 1970-01-01
      相关资源
      最近更新 更多