在构建过程中捕获特定基础成员的异常

Catching exceptions for specific base members during construction

本文关键字:成员 异常 构建 过程中      更新时间:2023-10-16

我知道,给定一个类foo与一个基类base,我可以写

foo(/*real code has parameters here*/) try : 
   base(), /*real code has parameters here*/
   anotherMember(someFunction(/*some parameters here*/))
{
} catch (...){
}

但是是否有一种语法,我可以用来把try catch块围绕anotherMember,而不是整个基本成员列表和构造函数体?

(注意anotherMemberconst类型,因此需要在初始化器列表中)

这样做不太有意义,但由于anotherMember从函数初始化,您可以将try..catch放在该函数中。我假设它有一个不抛出的复制构造函数和一个可能抛出的复制构造函数,它接受参数,你的someFunction调用那个。

如果anotherMember不能正确构建,你想做什么?

您的明显替代方案是将anotherMember包装在某种智能指针中,如果初始化失败,可能使其"可空"。如果您创建了自己的特殊对象,它将包含抛出的异常消息。

struct AnotherTypeWrapper
{
    std::unique_ptr< AnotherType > ptr;
    std::string errorMsg;
    AnotherTypeWrapper( Args&& args... ) // ok probably not variadic
    {
       try
       {
          ptr.reset( new AnotherType( std::forward(args) ) ); // or whatever the syntax
       }
       catch( std::exception const& err )
       {
          errorMsg = err.what();
       }
    }
};

差不多。