I stumbled across some peculiar behavior in an old program and am figure out why G++ and CLang++ allow it to happen. I have some global variables declared and initialized before main(). The odd part is that they are initialized through a static std::map which is being populated at the same time using the subscripting operator. Everything seems to be in the correct place as soon as main() runs, with the size of the map showing the correct number of populated items as well as the variables containing the values shown before main().
#include <map>
#include <iostream>
static std::map<int, const char*> staticMap;
const char* const a = staticMap[0] = []()->const char* {return "a";}();
const char* const b = staticMap[1] = []()->const char* {return "b";}();
const char* const c = staticMap[2] = []()->const char* {return "c";}();
const char* const d = staticMap[3] = []()->const char* {return "d";}();
const char* const e = staticMap[4] = []()->const char* {return "e";}();
int main() {
std::cout << "# Items: " << staticMap.size() << '\n' << std::endl;
std::cout << "Values:\n";
std::cout << "\"a\" = " << a << '\n';
std::cout << "\"b\" = " << b << '\n';
std::cout << "\"c\" = " << c << '\n';
std::cout << "\"d\" = " << d << '\n';
std::cout << "\"e\" = " << e << '\n';
std::cout << std::endl;
std::cout << "Map Contents:" << std::endl;;
for (unsigned i = 0; i < 5; ++i) {
std::cout << "\t" << staticMap[i] << std::endl;
}
return 0;
}
Here is the result after trying both G++ and CLang (I used the flags -std=c++11 -Wall -Werror -Wextra -pedantic-errors):
# Items: 5
Values:
"a" = a
"b" = b
"c" = c
"d" = d
"e" = e
Map Contents:
a
b
c
d
e
Is this something inherently allowed in C++? I even went so far as to create my own map type and got the same results but am still not sure if it's behavior I can rely on.
Aucun commentaire:
Enregistrer un commentaire