c++ - 静态初始化的对象不能放在 try block 中

标签 c++ exception global-variables try-catch

我正在阅读《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/

相关文章:

c++ - Eclipse C++ 头文件和文件问题

android - 如何使用PackageManager.setComponentEnabledSetting

python - 全局变量名和不同函数的问题(使用 Python)

php - PHP中的全局变量被认为是不好的做法吗?如果是这样,为什么?

Java String.format 无法完全格式化日期和整数

c++ - 实现在 C++ 类中使用的全局变量的最佳方法

c++ - WH_SHELL 的问题

c++ - 当您通过转换构造函数初始化 const 引用时会发生什么?

c++ - 链接错误 : collect2: error: ld returned 1 exit status

c# - C# 函数是否有标准的 "never returns"属性?