我正在阅读《Inside the C++ Object Model》这本书,我得到了一段如下:
There are a number of drawbacks to using statically initialized objects. For example, if exception handling is supported, these objects cannot be placed within try blocks. This can be particularly unsatisfactory with statically invoked constructors because any throw will by necessity trigger the default terminate() function within the exception handling library.
如果我没看错,那就是
MyGlobalObject obj;
int main()
{
try
{
// do something with obj here is unsatisfactory
}
catch(...){}
return 0;
}
不好。但我不知道为什么。为什么任何抛出都必须触发默认的 terminate() 函数。
最佳答案
这意味着你不能从静态初始化的对象中捕获异常,因为它们是在 main()
开始之前初始化的,这使得它不可能用 try{}
block 包围它们。
MyGlobalObject obj; // this initializes before main() starts
int main()
{
try
{
// too late to protect the static initialized global
// with this try block during its initialization
// but any operations you perform on it afterwards
// inside this try{} block will be fine.
}
catch(std::exception const& e)
{
}
}
一个解决方案是将静态对象放在函数中,如下所示:
MyGlobalObject& get_my_global_object()
{
// This will not initialize until this function
// is called for the first time.
static MyGlobalObject obj;
return obj;
}
int main()
{
try
{
// now if the global object throws during its
// initializatin the exception will be caught.
MyGlobalObject& obj = get_my_global_object();
}
catch(std::exception const& e)
{
}
}
关于c++ - 静态初始化的对象不能放在 try block 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44469228/