What is wrong with using a static member object with a class? - c++

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,

Most of the arguments against them are the same as for global variables:
Initialization order between different compilation units is undefined.
Initialization order inside one compilation unit may affect the behavior — thus non trivial ordering may be required.
If a constructor throws an exception you can't catch it, your program is terminated.
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.

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...

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.

Related

Static initialization order fiasco for built-in objects/libraries

If I have some variables that I'm initializing statically (before main begins), am I free to use any built-in stuff in these constructors, like <iostream> or <vector>?
The "static initialization order fiasco" occurs because the order in which static variables are initialized (among different translation units) is undefined.
So what if something benign like
std::cout << "Hello" << std::endl;
happens to rely on some static variable inside <iostream> being initialized ahead of time? (I'm not saying it does, but assume it did.) What's to say that these static variables inside built-in libraries are initialized before my own static variables? Like inside say "Person.cpp" or whatever.
Edit: Is std::cout guaranteed to be initialized? was suggested as a duplicate to this question. However, I think my question is slightly broader in scope because it asks about any standard built-in library, rather than just <iostream>.
The C++ standards make no strong statements of the behavior of the program before the start of main, or after main has completed.
In experience, I have found a number of issues where the C++ runtime has destroyed some object (e.g. resources used for management of std::mutex), which have created a deadlock in the destruction of a complex type.
I would recommend the following pattern for static's
C++ creates objects declared static in a function in the order they are executed. This leaves a pattern which will ensure that objects exist as they are needed.
AnObject * AnObject::getInstance() {
static AnObject a;
return &a;
}
This should be executed to get hold of the global, and will occur at the point when getInstance() is called.
C++ 11 onwards
This code is guaranteed to be thread-safe, where if multiple threads of execution arrive in getInstance, only one will construct the object and the rest will wait.
Pre C++ 11
Creating this pattern replaces ill-defined order with thread safety issues.
Luckily, it will be possible to create a criticalsection/mutex primative in main, which is able to arbitrate.
In some OSs (e.g. InitializeCriticalSection and Windows), these locks can safely be created before main as static variables.
AnObject * AnObject::getInstance() {
EnterCriticalSection( &aObjectcrit );
static AnObject a;
LeaveCriticalSection( &aObjectcrit );
return &a;
}
Assuming you have initialized aObjectcrit either in or before this function is called.
The result of this pattern is a form of onion construction, where objects are required in the order they are needed, and when the program exits, they are destroyed in the reverse order they were created in.
You're confusing objects (std::cout) and types (std::vector). The former is covered by the linked question, and the latter is a type. Static initialization applies to objects, but not to types.

C++ static member variable scope

The title basically says it all, i wonder when static members of a c++ class are initialized and when they go out of scope.
I need this for the following problem. I have many objects of a class Foo and each object needs access to a resource, encapsulated by another class Bar. Synchronization is not an issue, so i want all objects to share the same Bar instance.
I'm using a simple managed pointer for reference counting.
Can i do the following:
class Foo {
private:
static managed_pointer<Bar> staticBar;
public:
Foo() {
if(!staticBar)
staticBar = new Bar;
}
/*
* use staticBar in various non-static member functions
*/
};
managed_pointer<Bar> Foo::staticBar = NULL;
the managed_pointer staticBar should delete the Bar object as soon as it goes out of scope - but when does this happen? when the last instance of Foo is destructed? on application exit?
Thanks for your advice!
statics and globals are initialized right before the program starts (before main is called, the program actually starts before that) and go out of scope after main exits.
Exceptions - local statics (static variables declared inside functions) and unused template class staticmembers.
It has nothing to do with the number of instances.
The standard does not specify a precise order of initialization, it is implementation specific. They will be instantiated at the start of the program and deallocated at the end.
You have to be very careful with what you are doing, because if you have some other static objects that rely on this object to exist, it's UB. There is no telling in what order they will be initialized.
You could possibly look into something like boost::call_once to ensure it's initialized once, but I wouldn't rely on the order the statics are initialized.
For all I know, you code would work, but I've been bitten by the static initialization issue before so I wanted to warn you.
EDIT: Also in your code, when the managed_ptr will go out of scope (end of program), it will delete the memory allocated automatically. But you should not do anything non-trivial in Bar's destructor as you may trigger UB by calling into other free'd instances or even code that has been removed (as it happened to me once where a dynamic library had been removed). Essentially you are in a minefield, so watch out.
The first thing that pops out of your question is the common misconception that scope and lifetime are equivalent concepts. They are not. In some cases as with local variables, the lifetime is bound to a particular context, but that is not always the case.
A class static member variable has class scope (it is accessible anywhere in the program) and static lifetime, which means that it will be initialized in order with respect to the other static variables in the same translation unit, and in an undefined order with respect to other static variables in other translation units, before main (caveat: initialization need not be performed before the first statement in main, but it is guaranteed to be before the first odr-use of the variable).

C++: Is it bad to use global variables that are pointers to instantiations of single-instance-only classes?

In my program, I've got a bunch of classes that will only ever have one created instance for the duration of the program. They are created only once on initialization, and destroyed only once on closing.
These classes all tend to present really broad functionality that is used by many different parts of the program, and so having them as global externs is really clean and easy to understand, rather than encapsulating them in another class or passing around pointers.
The program is multi-threaded, and all of these classes contain their own mutex for access.
Are there any problems with this approach? If so, what are the recommended alternatives.
Use a singleton pattern as follows:
Foo& foo() { static Foo x; return x; }
This is completely thread-safe. See here: G++ 4.6 -std=gnu++0x: Static Local Variable Constructor Call Timing and Thread Safety
It is guaranteed by the current standard.
Furthermore this is superior to static initialized global variables because if you have multiple of the above they will be initialized lazily in the correct dependency order.
Foo& foo() { static Foo x; return x; }
Bar& bar() { static Bar x; return x; }
and in Bar::Bar there is a call to foo(), then the Foo singleton will be created before Bar.
If I had of used global variables:
// Foo.cpp
Foo foo;
// Bar.cpp
Bar bar;
No such ordering is guaranteed.
3.6.2 Initialization of non-local variables
...the initialization of a variable is indeterminately sequenced with respect to the initialization of a variable defined in a different translation unit....
You can use a Singleton, but be sure of thread safety. For a tutorial, take a look at SINGLETON PATTERN - 1. THREAD SAFETY
An example would be
static SomeSingleton* getInstance()
{
lock_mutex();
if(!pInstance_)
pInstance_ = new SomeSingleton();
unlock_mutex();
return pInstance_;
}
By using global variables in your classes you make them difficult to test. Their behaviour now depends on a global state, which makes it difficult to reason about them. One class depends on the global variable. Another class depends on it, too. Both can change the state of the global variable any time. In essence you have a created a mutual dependency between both classes. With every access to the global variable you are one step closer to one version of the dependency hell.
You have mentioned that you do not want to pass them around as pointers. Actually I would prefer that method. By explicitly passing a dependency (your global variables) to a method or constructor you tell the world about it. If you need to pass ten dependencies to your method, you might want to rethink your solution. It might be a lot of work, but helps to improve the architecture of your program.
You have written that your classes "tend to present really broad functionality". This might be an indicator that they should be broken down into smaller components, so that you only have to pass around the functionality that you actually need.
My advice is that
you should avoid using global variables, especially in the form of singletons
try to find out more about dependency injection to properly pass around your dependencies
watch video Don't look for things (Clean Code Talks, Misko Hevery)
c++ has big problems with order of calling global objects constructors
somebody calls it "global initialization fiasco"
It's not related with multithreading, but related with initialization
If your program has many global objects then it may cause some problems (of course there are some methods to solve that problem)
You can use pattern 'singleton' but I'm not sure will it be useful in your case

Is there an issue with this singleton implementation?

I've typically gotten used to implementing a singleton pattern in this manner because it's so easy:
class MyClass
{
public:
MyClass* GetInstance()
{
static MyClass instance;
return &instance;
}
private:
//Disallow copy construction, copy assignment, and external
//default construction.
};
This seems significantly easier than creating a static instance pointer, initializing it in the source file, and using dynamic memory allocation in the instance function with guards.
Is there a downside that I'm not seeing? It looks thread-safe to me because I would think the first thread to get to the first line would cause the instantiation - and it seems nice and concise. I figure there has to be a problem I'm not seeing since this is not common though - I'd like to get some feedback before I keep using it
This is not an inherent threadsafe solution: while constructing the instance, another thread can preempt and try to get the instance, resulting in either a double instance or in using an unconstructed instance.
This is handled by several compilers by adding a guard (in gcc, I think there is a flag to disable this) because there is no way to guard this with a userdefined mutex.
The downside is that you have no control over exactly when the object is destroyed. This will be a problem if other static objects try to access it from their destructors.
A C++11 compliant compiler must implement this in a thread-safe way; however, older compilers might not. If you're in doubt, and you don't especially want lazy initialisation, you could force the object to be created by calling the accessor before starting any threads.
There are two issues in the interface:
You should return a reference
You should make either the destructor or the delete operator private
Also, there is a slight risk of attempting to using this class after it's been destructed.
Regarding your multi-threading concerns (and initialization I guess): it's fine in C++11 and have been fine for a long time on good C++ compilers anyway.
Aside from in a multi-threaded scenario - no. Well - let me qualify this, construction is lazy (so the first call may have a hit) and destruction - well, there is no guarantee (aside from it will be - at some point)
Generally speaking, qualifier static for local variable in a method doesn't guarantee that the variable is created only once. If the method is called by different threads, it could be created once for each thread so many times, as many threads called it. It should be not confused with static member of the class, which is created once before program is started. Thread safety of local static variables depends on particular realization of c++. Useful link : Are function static variables thread-safe in GCC?
Hope it helps.

static variable vs. member

If you have data for a class that will be modified and needs to be retained throughout the program, but is only used in one member function, is it preferred to make that variable a local static variable of the routine that it is in or make it a member of the class?
The question isn't "will the data be used throughout the program", but rather "if you make two objects of this class, do you want them to share this data?" If yes, make it static. If no, don't.
I would argue that in most cases, you should never use a local static variable, and instead use a static member variable. Then the question degenerates to if that variable should be shared among the class instances or not.
Declaring a local variable as static means your method now has state, separate from the object's state. It can lead to many mistakes when maintaining this code (such as copy constructor implementation, assignment, serialization) and when reading it (unclear method behavior).
Avoid using static locals unless you have some good reason (the only one I can think of is single threaded singletone implementation).