These are two questions about static locals that have always bothered me and I haven’t found a definitive answer to:
Question 1:
struct Test
{
static inline const char* name()
{
static const char* nameValue = "Name of Test";
return nameValue;
}
};
Since the method is inline, there should be a copy of this method in each compilation unit that calls it. But, there must be only one instance of the local static variable nameValue (correct me if I am wrong). How is this achieved? We have many instances of a function generated, but all of them refer to the same static local. Does the compiler maintain a global table of static locals associated with each function by name?
Question 2:
struct Init
{
Init() {printf("init created\n");}
~Init() {printf("init destroyed\n");}
};
struct Test
{
static void func()
{
static Init init;
}
};
The static local Init object is constructed only once, on the first call of func(). How does the compiler know when is the first call to func()? Does it maintain a flag at runtime, whether this is the first call of this func?
These are really two unrelated questions.
For the first, there are various solutions. Perhaps the most frequent
are something called weak symbols. Roughly speaking, the compiler
generates an instance under a specific name in every object file that
uses the function, and the linker throws out the duplicates, and only
keeps one in the final program.
For the second, the usual solution is to generate a boolean variable
associated with the object, and tests this when the object comes into
scope.