Global object constructor can throw exception

A C++ constructor can throw an exception and there is at least one static/global instance of this class (or a class derived from this class).

This is unsafe usage because it can cause an exception to be thrown in a context where exceptions are not allowed, such as the static elaboration performed when an executable or a dynamic library is loaded. If an exception were thrown in such a context, the C++ runtime would cause the application to fail.

ID

Observation

Description

1

Exception throw

This shows where the exception was thrown

2

Definition

This shows where the constructor was defined

Example

          
#include <stdio.h>

class Bomb { // bad class throws exception from constructor
public:
int x;
    Bomb() : x(0) { throw "boom"; }
    ~Bomb() { }
};

// Variable declaration that will throw exception
// during static elaboration before main is called
Bomb myBomb;

int main(int argc, char **argv)
{
    printf("hello, world\n"); // never gets here
}
        

Copyright © 2010, Intel Corporation. All rights reserved.