Vadim
Vadim

Reputation: 1241

Inline function returning statically created object

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?

Upvotes: 3

Views: 671

Answers (4)

fredoverflow
fredoverflow

Reputation: 263118

What is the point of the dynamic allocation, if I may ask? I would get rid of it:

inline Config& config()
{
    static Config c = Config();
    return c;
}

If Config is not a POD, you can even just say static Config c; and get the same semantics.

Upvotes: 1

Dennis Zickefoose
Dennis Zickefoose

Reputation: 10969

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.

bool initialized = false;
Config* c;

inline Config& config() {
    if(!initialized) {
        c = new Config();
        initialized = true;
    }
    return *c;
}

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.

Upvotes: 3

Necrolis
Necrolis

Reputation: 26171

It depends on the compiler, but from what I've seen in MSVC, it'll inline two globals to do this (at an assembly level). one is a bool to indicate if the static var was inited, and the other for the actual static var your setting.

however, one should note that inline is more a hint these days, so the function might not ever get inlined, just cause the compiler decided that inline the constructor for the the object and the static handling code would cause too much bloat etc.

Upvotes: 2

Puppy
Puppy

Reputation: 146910

If the inliner couldn't handle such trivial cases as this, no functions would ever get inlined at all.

Upvotes: 1

Related Questions