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

前端 未结 4 1405
北海茫月
北海茫月 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:37

    Dynamically allocate the instance using new:

    std::unique_ptr instance;
    try
    {
        instance.reset(new MyClass(3, 4, 5));
    }
    catch (const MyClassException& ex)
    {
        std::cerr << "There was an error creating the MyClass." << std::endl;
        return 1;
    }
    // use instance as needed...
    

提交回复
热议问题