Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's consider a C++ class. At the beginning of the execution I want to read a set of values from an XML file and assign them to 7 of the data members of this class. Those values do not change during the whole execution and they have to be shared by all the 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)

like image 500
user48716 Avatar asked Dec 23 '08 19:12

user48716


3 Answers

As others have mentioned, the use of static members in this case seems appropriate. Just remember that it is not foolproof; some of the issues with global data apply to static members:

  • You cannot control the order of initialization of your static members, so you need to make sure that no globals or other statics refer to these objects. See this C++ FAQ Question for more details and also for some tips for avoiding this problem.
  • If your accessing these in a multi-threaded environment you need to make sure that the members are fully initialized before you spawn any threads.
like image 72
zdan Avatar answered Sep 22 '22 17:09

zdan


Sounds like a good use of static variables to me. You're using these more as fixed parameters than variables, and the values legitimately need to be shared.

like image 35
David Thornley Avatar answered Sep 18 '22 17:09

David Thornley


static members would work here and are perfectly acceptable. Another option is to use a singleton pattern for the class that holds these members to ensure that they are constructed/set only once.

like image 40
Rob Prouse Avatar answered Sep 19 '22 17:09

Rob Prouse