C++ static variable declaration - difference between module vs function

37 Views Asked by At

This is probably answered on the web somewhere, but I had trouble querying via search engine.

In order to adhere to the construct-on-first-use idiom, I have moved static object declaration from the module scope (top of the file) to within a local function that returns a reference, for each. The idea being I can somewhat control the order things are constructed based on when those objects are first used.

What I'm trying to understand is what is the cost/benefit of one versus the other? Are there any?

(These are not accessed via multiple threads)

Example: Declared:
static CLASS_T object1;

Accessed:
object1.Do();

vs.

Declared:

    static CLASS_T & GetObject1()
    {
        static CLASS_T object1;
        return object1;
    }

Accessed:
GetObject1().Do();

Everything compiles fine, I just want to understand if there are tradeoffs or anything I'm not expecting that I should be aware of.

This post is related Difference between Static variable declared in different scopes, but I'm curious if access via reference makes any difference, and if this is truly supporting the construct-on-first-use idiom.

0

There are 0 best solutions below