inline Config& config()
{
static Config *c = new Config();
return *c;
}
The function above returns a pointer to class Config, created once when function calls.
Will the C++ compiler be able to inline this function correctly?
I mean c is static object, and creating it at first time will lead to inlined new Config() somewhere in the code. But when the function is called second time, what will be at the place of the config()? Inlined c? Or a function call?
You seem to have a slight misunderstanding about how such static variables work. It seems like you’re thinking the compiler emits one set of code the first time the function is called, and another set every other time. That’s not the case. You might consider the following transformation.
That’s a simplification, but it gets the point across. The function tracks whether or not the static has been initialized, and if it hasn’t, does so. It does this check every time you call the function.
With that in mind, the existance of a static variable has no direct impact on the inlinability of a particular function… the compiler will simply inline the check along with everything else. The question is simply, does this new expanded code still meet the requirements the compiler sets forth for inlining a function? It might not, but either way the visible result should be the same.