tags:

views:

179

answers:

4

I have heard that using static member objects is not a very good practice.

Say for example, I have this code:

class Foo {
...
static MyString str;
};

I define and initialize this variable in the implementation file of this class as:

MyString Foo::str = "Some String"; // This is fine as my string API handles this.

When I run this code, I get a warning:

warning:'Foo::str' requires global construction.

I have quite much of such members in my class, what is the best way to handle this.

Thanks,

+2  A: 

Using a static member, you are not guaranteeing thread safety, imagine two threads trying to access the static member - now what would be the value of that member - was it the one from thread x or thread y, this also induces another side-effect, race conditions, where one thread modifies the static member before the other thread completes... in other words, using a static member can be hazardous...

tommieb75
It's true not only for static members but for any shared data between threads. I think this doesn't answer the question properly as thread safety has nothing to do with static members initialization.
ybungalobill
+8  A: 
ybungalobill
While I appreciate your list, those are mostly implementation details. From a functional point of view, this also affects reentrance, and thus testability and multithreaded programs.
Matthieu M.
+3  A: 

The biggest reason for concern with this example is that constructing the static member object happens before main() and destruction happens after main() (or when you call exit()). So far, that's a good thing. But when you have multiple objects like this in your program, you risk a bug where code attempts to use an object that has not yet been constructed or has already been destroyed.

The C++ FAQ Lite has some helpful discussion on this topic, including a workaround/solution. Recommended reading is questions 10.14 through 10.18. 10.17 is most directly applicable to your example.

aschepler
+1  A: 

As an example, it is required to know the number of instances of a class. This would require a class static member to track the count of instances.

There is nothing wrong in having a static member of a class if the problem solution requires such a design. It's just that the nitty gritties have to be taken care as mentioned in other posts.

Chubsdad