CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

Avoid const global variables or local statics with dynamic initialization

Open gdr-at-ms opened this issue 8 years ago • 8 comments

Add a rule discouraging variables with static storage duration that need dynamic initialization. Add a rule banning user-written constructors that mimic implicitly generated constructors but without adding value [which can make its use create a dynamic initialization].

gdr-at-ms avatar Jul 06 '16 15:07 gdr-at-ms

I would guess that this rule is mainly to avoid initialization order issues with global variables, but local statics are sometimes used to avoid the initialization order issues. Do you you see this use of local statics as an exception?

vcato avatar Jul 06 '16 16:07 vcato

This is meant to apply to 'const' local statics -- not general local statics. A dynamic initialization incur some overhead (since it has to be guarded by a mutex of sort to ensure thread safety) and drags in some runtime.

gdr-at-ms avatar Jul 06 '16 16:07 gdr-at-ms

Does this imply that making the local static non-const is a reasonable alternative?

vcato avatar Jul 06 '16 16:07 vcato

Well, it is not really an alternative if the data is intended to be non-modifiable. Some non-const local statics have their uses as singleton, but that is not the subject of this rule here.

gdr-at-ms avatar Jul 06 '16 17:07 gdr-at-ms

Do you see a general alternative? Let's take the example of a math function:

    double important_number()
    {
        static const double result = sqrt(2.0)/2.0;
        return result;
    }

Let's assume that the function is complex enough that there is a performance benefit to avoiding repeated calculations. Do you see a good alternative, or is this an exception to the rule?

vcato avatar Jul 06 '16 19:07 vcato

If you can't make the function constexpr so that you get a compile-time constant, you have an exception on your hands. But, that is not the focus of this issue. I would suggest you hold your fire until you see a concrete formulation of the rule, or else we digress on exceptions...

gdr-at-ms avatar Jul 06 '16 19:07 gdr-at-ms

Got it. I only recently started trying to get involved with this project, so I'm not familiar with the procedures. I was asking questions trying to understand what form these rules would take, but it sounds that like information is forthcoming. Thanks for your time.

vcato avatar Jul 06 '16 20:07 vcato

Note that the example of creating static tables is often covered using compile-time code (e.g., consteval).

hsutter avatar Jul 30 '20 18:07 hsutter