Why can I populate variables via std :: map before main ()?

I came across some kind of peculiar behavior in the old program and realized why g ++ and CLang ++ allow this to happen. I have some global variables declared and initialized before main (). The odd part is that they are initialized via a static std :: map, which is populated simultaneously using the signature operator. Everything seems to be in the right place as soon as main () is started with the size of the map showing the correct number of elements filled, as well as 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

- ++? , , , .

+4
3

, . , TU ( staticMap , ), , .

, , - , :

const char* a = staticMap[0] = "a";
const char* b = staticMap[1] = "b";
const char* c = staticMap[2] = "c";
const char* d = staticMap[3] = "d";
const char* e = staticMap[4] = "e";

:

const char *dummy = (
    staticMap[0]="a",
    staticMap[1]="b",
    staticMap[2]="c",
    staticMap[3]="d",
    staticMap[4]="e");

, , , main, :

class MyCode
{
    MyCode()
    {
        // here be your code
    }
};
static MyCode m;

, , main, , . , " " locals main .

+9

, main. ++ /, ( std::map::operator[] - )

:

int foo()
{
   std::cout << "foo";  // You could fill your map here 
   return 42;
}

int bar = foo(); // allowed

int main() {

    return 0;
}

++ :

struct foo
{
   foo()
   {
       std::cout << "foo"; // You could fill your map here  
   }
};

foo f;

int main() {

    return 0;
}

foo(), .

:

, :

const char* const a = staticMap[0] = "a";
const char* const b = staticMap[1] = "b";
const char* const c = staticMap[2] = "c";
const char* const d = staticMap[3] = "d";
const char* const e = staticMap[4] = "e";
+4

main(). , . main() , .

( ). , , .

, , , : , -.

0

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


All Articles