Are static data members safe as C ++ default arguments?

Do I have to worry about static initialization fiasco when using a static data member as the default argument value? For instance:

class Thing {

    static double const default_blarg;  // initialized in another file

    void run(double blarg=default_blarg);

};

I know that it default_blargwill be initialized at a basically undefined time point of the link, but I'm not sure when the default argument is initialized run. If it is default_blarginitialized at some point that can be up , what approach could I use to safely display the default values ​​as part of the class interface without repeating it? Would using constexprfor a static data member make it safe?

Please note that I know that this can lead to very confusing behavior if default_blargthere wasn’t const (why is it) and I am not trying to use a non-static data element.

+4
source share
2 answers

You still need to worry about the static initialization fiasco. Let's say you have a.cpp and b.cpp. In a.cpp you have

double const Thing::default_blarg = 0;

Now in a.cpp, any call runafter this point will have an initialized default value, and you're good to go. Unfortunately, in b.cpp, you have another static object that instantiates Thingand calls run.

, . b.cpp , default_blarg , undefined.

,

. , , default_blarg (, , ), .

+4

++ 11, 8.3.6/9:

, .

Thing::default_blarg Thing::run, .

+2

Source: https://habr.com/ru/post/1654048/


All Articles