JohnTortugo
JohnTortugo

Reputation: 6625

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...

Upvotes: 1

Views: 1179

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477600

The anonymous namespace gives the contained objects internal linkage, as their fully qualified name can never be known to anyone outside the translation unit. It's the sophisticated man's version of the old static in C.

Note that you do declare a global object of type StaticStruct, and its constructor (which runs before main() is called) calls test().

Upvotes: 1

James McNellis
James McNellis

Reputation: 355327

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.

Upvotes: 4

Related Questions