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,
Static classes have several limitations compared to non-static ones: A static class cannot be inherited from another class. A static class cannot be a base class for another static or non-static class. Static classes do not support virtual methods.
The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.
Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.
Explanation: The static member functions can't be virtual. This is a restriction on static member functions, since the definition should not change or should not be overridden by any other function of derived class.
Most of the arguments against them are the same as for global variables:
APPENDED: To handle this properly you must either make sure that above points don't apply to your code and ignore the warning, or redesign your program: Do you really need them static? Why not use const char* Foo::str = "Some String";
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With