如何捕获在初始化静态成员时抛出的异常 [英] How to catch exception thrown while initializing a static member
问题描述
我有一个类包含静态成员:
I have a class with a static member:
class MyClass
{
public:
static const SomeOtherClass myVariable;
};
其中我在CPP文件中初始化如下:
Which I initialize in the CPP file like so:
const SomeOtherClass MyClass::myVariable(SomeFunction());
问题是, SomeFunction()
来自注册表的值。如果该注册表项不存在,它将抛出异常。这会导致我的程序爆炸,而不给用户任何有用的输出...是否有一些方法我可以捕获异常,所以我可以记录它?
The problem is, SomeFunction()
reads a value from the registry. If that registry key doesn't exist, it throws an exception. This causes my program to explode without giving the user any useful output... is there some way I can catch the exception so I can log it?
推荐答案
我不喜欢 static
数据成员,初始化的问题是最重要的。
I don't like static
data members much, the problem of initialization being foremost.
class MyClass
{
public:
static const SomeOtherClass& myVariable();
};
const SomeOtherClass& MyClass::myVariable()
{
static const SomeOtherClass MyVariable(someOtherFunction());
return MyVariable;
}
这样,异常只会在第一次使用时抛出,对象将是 const
。
This way, the exception will be throw only on first use, and yet the object will be const
.
这是一个非常强大的习语延迟执行。它有一点开销(基本上,编译器每次进入方法检查一个标志),但更好的担心正确性;)
This is quite a powerful idiom to delay execution. It had a little overhead (basically the compiler checks a flag each time it enters the method), but better worry about correctness first ;)
如果这是从多线程调用:
If this is called from multiple threads:
- 如果您的编译器处理它,
- 可以在
中使用
boost :: once
,可以使用本地线程存储(无论如何都是常量) library - 因为它是
const
,你可能不在乎它是否初始化了多次,除非someOtherFunction
不支持并行执行(要小心资源)
- if your compiler handles it, fine
- if your compiler does not, you may be able to use local thread storage (it's const anyway)
- you could use
boost::once
in theBoost.Threads
library - since it's
const
, you may not care if it's initialized multiple times, unlesssomeOtherFunction
does not support parallel execution (beware of resources)
指南:只对简单对象使用 static
或全局
变量 local static
变量来延迟执行,直到可以捕获结果异常。
Guideline: only use static
or global
variables instantiation for simple objects (that cannot throw), otherwise use local static
variables to delay execution until you can catch the resulting exceptions.
这篇关于如何捕获在初始化静态成员时抛出的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!