Catching exceptions from a constructor means that my instance is out of scope afterward(从构造函数捕获异常意味着我的实例之后超出范围)
问题描述
我有一个类,它的构造函数可能会抛出异常.下面是一些可以捕获异常的代码:
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 (MyClassException& ex) {
cerr << "There was an error creating the MyClass." << endl;
return 1;
}
但是当然在 try/catch 之后没有代码可以看到 instance 因为它现在超出了范围.解决此问题的一种方法是分别声明和定义 instance:
But of course no code after the try/catch can see instance because it’s now out of scope. One way to resolve this would be to declare and define instance separately:
MyClass instance;
try {
MyClass instance(3, 4, 5);
}
...
除了我的类没有合适的零参数构造函数.事实上,这里的这种情况是唯一一个这样的构造函数甚至有意义的情况:MyClass 对象旨在是不可变的,从某种意义上说,它的数据成员在构造后都不会改变.如果我要添加一个零参数构造函数,我需要引入一些实例变量,例如 is_initialized_ 然后检查每个方法以确保该变量之前是 true进行.对于这样一个简单的模式来说,这似乎太过冗长了.
except that my class doesn’t have the appropriate zero-argument constructor. In fact, this case right here is the only one in which such a constructor would even make sense: the MyClass object is intended to be immutable, in the sense that none of its data members change after construction. If I were to add a zero-argument constructor I’d need to introduce some instance variable like is_initialized_ and then have every method check to make sure that that variable is true before proceeding. That seems like far too much verbosity for such a simple pattern.
处理这种事情的惯用方式是什么?我是否需要接受它并允许在初始化之前声明我的类的实例?
What is the idiomatic way to deal with this kind of thing? Do I need to suck it up and allow instances of my class to be declared before they’re initialized?
推荐答案
您应该在 try 块中内做您需要做的一切:
You should be doing everything you need to do inside the try block:
try {
MyClass instance(3, 4, 5);
// Use instance here
}
catch (MyClassException& ex) {
cerr << "There was an error creating the MyClass." << endl;
return 1;
}
毕竟只有在try块内,instance才被成功创建,可以使用.
After all, it is only within the try block that instance has been successfully created and so can be used.
我确实想知道您的 catch 块是否真的在处理异常.如果你不能做任何事情来解决这种情况,你应该让它传播.
I do wonder whether your catch block is really handling the exception. If you can't do anything to resolve the situation, you should be letting it propagate.
这篇关于从构造函数捕获异常意味着我的实例之后超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从构造函数捕获异常意味着我的实例之后超出范围
基础教程推荐
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
