static struct in anonymous namespace
-
12-12-2019 - |
Question
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.
OTHER TIPS
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()
.