☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

全局对象的初始化过程不可抛出异常

7.7 ID_throwOutOfMain
目录 › next › previous

初始化全局对象时抛出的异常无法被处理,会导致程序异常终止。

本规则是 ID_uncaughtException 的特化。

示例:

struct G {
    G() noexcept(0);   // May throw exceptions
};

static G g;   // Non-compliant

int main() {
    ....
}

如果例中全局对象 g 的构造函数抛出异常,会引发 std::terminate 函数的执行,使程序异常终止。

应改为:

G* getG() {
    try {
        static G g;
        return &g;
    } catch (Exceptions&) {  // Exceptions thrown by ‘G::G()’
        ....                 // Handle the exceptions
    }
    return nullptr;
}

int main() {
    if (!getG()) {
        return 1;     // Good, exit gracefully
    }
    ....
}

相关

ID_uncaughtException

依据

ISO/IEC 14882:2003 15.3(9)-implementation ISO/IEC 14882:2003 15.5.1(2)-implementation ISO/IEC 14882:2011 15.3(9)-implementation ISO/IEC 14882:2011 15.5.1(2)-implementation

参考

MISRA C++ 2008 15-3-1 SEI CERT ERR58-CPP
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.