Search code examples
c++initializationstatic-initialization

static struct in anonymous namespace


that this snippet of code actually do?

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;

void test();

namespace {
    static struct StaticStruct {
        StaticStruct() { 
            test(); 
        }
    } TheStaticSupport;
}


int main(void) {



    return 0;
}


void test() {
    printf("testing function\n");
}

why does the test function actually get called? and why use the "anonymous" namespace? I found this piece of code in an open source project...


Solution

  • This:

    static struct StaticStruct {
        StaticStruct() { 
            test(); 
        }
    } TheStaticSupport;
    

    Is equivalent to this:

    struct StaticStruct {
        StaticStruct() { 
            test(); 
        }
    };
    
    static StaticStruct TheStaticSupport;
    

    It defines a type named StaticStruct and an instance of the type named TheStaticSupport with internal linkage (though, since it is declared in an unnamed namespace, the static is redundant).

    The constructor for TheStaticSupport is called before main() is entered, to construct the object. This calls the test() function.