Static order initialization fiasco, iostream and C ++ 11

According to the C ++ 11 specification:

The results of inclusion <iostream>in the translation block should be as if <iostream>defining an instance ios_base::Initwith a static storage duration. Similarly, the entire program should behave as if there was at least one instance ios_base::Initwith a static storage duration

This means that if my code looks like this:

// A.cpp
#include <iostream>
using namespace std;
unsigned long foo() {
    cerr << "bar"; 
    return 42;
}

and

// B.cpp

using namespace std;
extern unsigned long foo();

namespace {
unsigned long test() {
    int id = foo();
    return id;
}

unsigned long id = test();
}


int main() {
     return 0;
}

then it should be safe for me to call cerrwithout the risk of a static initialization fiasco.

Sorry, this segfaults code ... Why? I don't think gcc 6.2.1 decided to ignore the C ++ 11 specification, and I included <iostream>in A.cpp. According to the specification, this should be enough.

+4
1

:

- ios_base:: Init, . 293)

293) , , .

, , iostreams , main. , , <iostream>.

!

foo() B.cpp ios_base::Init, A.cpp, .

+6

Source: https://habr.com/ru/post/1658358/


All Articles