Should I use static data items? (C ++)

Consider the C ++ class. At the beginning of the run, I want to read a set of values ​​from an XML file and assign them to 7 data members of this class. These values ​​do not change throughout the execution, and they must be used by all objects / instances of the class in question. Are static data members the most elegant way to achieve this behavior? (Of course, I do not consider global variables)

+5
source share
8 answers

As already mentioned, the use of static elements in this case seems appropriate. Just remember that this is not perfect; Some global data issues relate to static members:

  • You cannot control the initialization order of your static members, so you need to make sure that no global or other statistics are related to these objects. See this C ++ FAQ for more details, as well as some tips for fixing this issue.
  • If you are accessing them in a multi-threaded environment, you need to make sure that the members are fully initialized before creating any threads.
+5
source

. , , .

+3

. singleton pattern , , , / .

+3

. .

, , , : .

Factory Factory . Factory , .

, , .

PS. singletons .

+3

. , () . , , - "" -, , .

, , - .

+2

XML 7 . , / , .

, , . , . ?

. , , . , - ( ), (, XML ), - , .

+2

, - , . / . ++ , . , , singleton, , , . , :

  • xml_stuff.
  • ++ - ( ).

:

class xml_stuff {
public:
    xml_stuff() {
        // 1. touch all members once
        // => 2. they are created before used
        // => 3. they are created before the first xml_stuff instance
        // => 4. they will be destructed after the last xml_stuff instance is 
        //       destructed at program exit.
        get_member1();
        get_member2();
        get_member3();
        // ...
    }  

    // the first time their respective function is called, these
    // objects will be created and references to them are returned.
    static type1 & get_member1() { static type1 t; return t; }
    static type2 & get_member2() { static type2 t; return t; }
    static type1 & get_member3() { static type1 t; return t; }
    // ... all other 7 members
};

, xml_stuff:: get_memberN(), xml_stuff, xml_stuff. , , , undefined ++.

+1

While you are thinking about testability, and you have another way to set static variables besides reading in a file, plus you don’t rely on benig data without any changes for the whole duration of the process - you should be fine.

I found that thinking about writing tests when you design your code helps keep the code well-designed and reusable.

0
source

All Articles