Catching exceptions from a constructor means that my instance is out of scope afterward

前端 未结 4 1394
北海茫月
北海茫月 2020-12-11 21:18

I have a class whose constructor may throw an exception. Here’s some code that will catch the exception:

try {
    MyClass instance(3, 4, 5);
}
catch (MyClas         


        
4条回答
  •  时光说笑
    2020-12-11 21:45

    A variant of Remy's answer, but saving a dynamic allocation using std::optional:

    std::optional instance_opt;
    try {
        // could use `instance = MyClass(3, 4, 5)`, but that requires you to write a move constructor
        instance_opt.emplace(3, 4, 5);
    }
    catch (const MyClassException& ex) {
        std::cerr << "There was an error creating the MyClass." << std::endl;
        return 1;
    }
    MyClass& instance = *instance_opt;
    // use instance as needed...
    

提交回复
热议问题