Search code examples
c++static-data

Implementation of static data member at c++


I'm working on multi-threading function which defined as a member function and using a common variable of the object.

I'm thinking about two approaches :

1. global variable

static int var = 0;
 class Object {
   void specialOp { var++; }
}

2. static data member

class Object {
   static int var = 0;
   void specialOp { var++; }
}

I prefer the second option but when I looked on the internet I didn't find the implementation of static data member to know if I need to care of locks or if the complexity is higher than using in a global variable.


Solution

  • The static keyword in C++ means different things depending on where it is used.

    1. In global scope, it defines a global variable without linkage (makes the variable inaccessible outside the current compilation unit of source and included header files)
    2. As a class member, it declares a global variable that can be accessed in any files using Class::variable but in accordance to the access specifiers of the class (need to declare it in a cpp file as well)
    3. In a function, declares a global variable that is only accessible inside the function. Different calls to the same function are guaranteed to access the same memory.

    None of the able addresses multithreading though. To address multi-threading, you have a few options:

    1. declare the variable thread_local. This means each thread gets its own version of the variable.
    2. protect multiple access either by using std::atomic or some other thread synchronization primitive like a std::mutex