What are the consequences of having a static pointer to this - c++

I have a class that contains functions that need to run as threads. The proper way to do this (form what I understand) is have these functions declared as static. To use methods from this class I need a to have an instance to that class, so I create a static variable that is initialized to self in the constructor. What are the implications in efficiency and program logic?
class Foo
{
private: Foo* this_instance;
Foo()
{
this_instance=this;
}
void FooBar()
{
...
}
static void* Bar()
{
if (this_instance==NULL) return 1; //throws are not catched are they?
this_instance->FooBar();
return 0;
}
}
Not actual code but to make my question clearer.
The application actually works and I checked it with helgrind/memcheck and the errors are not related to the issue at hand. I'm asking this question because all solutions seem like workarounds, including this one. Others are like the one mentioned by doctor love, other using helper static method.
I am wondering if my approach would result in epic failures at some point in time, for some reason unknown to me and obvious to other more experienced programmers.

You do not need functions to be static to use them in threads. You could bind instance functions or pass the this pointer, or use C++11 with a lambda.
If you use raw threads you will have to catch exceptions in the thread - they will not propagate to the code that started the thread.
In C++11 you can propagate the exceptions, using current_exception and rethrow_exception. See here
EDIT
If you have a static pointer for each type, you can only have one instance of it, yet your code does nothing to prevent the static pointer being reset. Why bother having a class instance in the first place - surely just pass in the parameters? I think it's cleaner to have free functions to do the work. If you think it's not worth the effort, it's your code. What do your co-workers think of your design?

Related

Is there a way to make global function/static member function callable once?

To clarify, I'm not talking about multi-threaded environment. I often come across a situation where I have to allocate some resources in an init function (and consequently release the resource in a terminate function) and where I would like to avoid calling it twice. I was wondering if there was something like a built-in keyword in C/C++ to make it callable once. Something more sophisticated than a static local variable that I would have duplicated across all my init functions like
static bool isInitialized = false;
if (!isInitialized) {
isInitialized = true;
//...
}
Or maybe it isn't that bad and I could hide this behind a macro CALLABLE_ONCE.
I'm open to any solutions from C/C++03/C++11/C++14.
EDIT:
The reason why I would be using the init/terminate scheme on the global scope would mainly be due to the fact that I tend to create namespaces for entities that shouldn't be instantiated more than once and avoid using singleton as encouraged on this post. Of course using a class would be easier as I would simply use the constructor/destructor, but how can one initialize (only once) this kind of entities(namespaces)?
There is std::call_once, although presented to be used with threads rather than just one thread application, it can be used by a one thread application too.
The one problem you may encounter is if it throws, then it is not considered initialized. You may protect the initialization function with a try/catch if required, though.
Also in your case you may want a public static function and another function that is private. The public static function would perform the std::call_once. Something like this:
class my_class
{
public:
static void init()
{
std::call_once(m_initialized, private_init);
}
private:
static void private_init()
{
... // init here
}
static std::once_flag m_initialized;
};
As you can see, it looks exactly the same as your function, except that the if() and flag switch are hidden. You could also keep the m_initialized flag in your first function as a static variable.
The one difference, though, is that the std::call_once is thread safe.

C++ : Is it bad practice to use a static container in a class to contain pointers to all its objects for ease of access?

I would like to know if it's bad practice to have a static container in a class to store all the pointers to the class' objects so they can all be easily accessed by the base classes of the program. This is for a game and I saw it on sdltutorials dot com, and I find it very useful. It would allow me to have a very neat structure for my game and I don't really see a downside doing this, but I know I have to be careful with "global" access and maybe there's a negative effect I'm not seeing right now.
Here is the context/example. The game has a base class with basic methods such as Loop(), Render(), PlayAudio(), CleanMemory(). The idea is to have individual objects to have the same methods being executed inside the base method. Example in pseudocode:
Game::Render() {
for (iterate all enemies in static container) {
current_enemy::Render();
}
}
To be sure, the static member inside the class would look like this:
static std::vector<Enemy*> EnemyList;
So this way, when your game is executing the base Render() method, for example, you can iterate all the enemies in the enemies' class static container and execute all their individual Render() methods, then do the same for environment objects, then for the player, etc.
I would just like to make sure I'm aware of any downside/complication/limitation I might encounter if I choose this method to build my game, because I don't see any right now but I know a have to be careful with static and global stuff.
Thanks very much for your time.
It is certainly convenient, however a static variable or a Singleton are nothing more than global variables; and having global variables comes with drawbacks:
the dependencies of a function become unclear: which global does it rely upon ?
the re-entrancy of a function is compromised: what if current_enemy.render() accidentally calls Game::Render() ? it's an infinite recursion!
the thread-safety of a function is compromised, unless proper synchronization takes place, in which case the serialized access to the global variable bog down the performance of your concurrent code (because of Amdahl's Law)
It might seem painful and pointless to explicitly pass a reference to an instance of Game wherever you need to, however it leaves a clear path of dependencies that can be followed and as the software grows you will appreciate explicitness.
And there is, of course, much to be said about transforming the program to have two instances of Game. While it might seem incongruous in this precise situation, in general it is wise not to assume that it will never be necessary in the future, for we are no oracles.
Different people may have different opinions about this. I can give you some advice on how to store your static objects in a better way.
Use the singleton pattern for a class which stores your objects:
class ObjectManager
{
private:
std::vector<Enemy*> enemies_;
std::vector<Friend*> friends_;
...
public:
void add(Enemy* e) { enemies_.push_back(e); }
...
const std::vector<Enemy*> enemies() const { return enmies_; }
...
private:
static ObjectManager* instance_;
public:
static ObjectManager* Get() { return instance_; }
static void Initialize() { instance_ = new ObjectManager(); }
}
You can access it like that (example with C++11 ranged-based for):
void Game::Render() {
for(auto e : ObjectManager::Get()->enemies()) {
e->Render();
}
}
This is especially convenient for subclasses which want to access information about the world. Normally you would have to give a pointer to ObjectManager to everyone. But if you have only one ObjectManager anyway the singleton pattern may remove clutter from your code.
Don't forget to create the singleton at the beginning of your program by calling ObjectManager::Initialize();.
I would not suggest doing this the way you are. At this point you may as well have a bare global variable in a namespace, it is the same thing you are doing right now.
I also do not suggest using singletons.
When should the Singleton pattern NOT be used? (Besides the obvious)
The best way to approach things is to do good old parameter passing (dependency injection) wherever possible. With careful design this is feasible system wide, and it avoids all the problems you have with globally accessible resources.
When you don't have the luxury of designing your system in such a way, and you are working within existing code that already has quite a bit of trouble with singleton dependence, or loss of locality between resources several levels removed from where they are needed (and you cannot afford to modify the interfaces to cascade dependencies downward) this may not be useful advice.
A middle-ground between bare global and singleton is the service-locator. Many people still consider service-locator an anti-pattern, but most people also agree that it is less bad than the singleton since it offers a certain level of abstraction and decouples creation from supplying the object which means you can offer up a derived class easily if your design or environment changes.
Here is a description of the pattern:
http://gameprogrammingpatterns.com/service-locator.html
And here is a discussion about the singleton vs service-locator.
If Singletons are bad then why is a Service Container good?.
I like the highest voted (but not accepted) answer best.

How does this code create an instance of a class which has only a private constructor?

I'm working on a sound library (with OpenAL), and taking inspiration from the interface provided by FMOD, you can see the interface at this link.
I've provided some concepts like: Sound, Channel and ChannelGroup, as you can see through FMOD interface, all of those classes have a private constructor and, for example, if you would create a Sound you mast use the function createSound() provided by the System class (the same if you would create a Channel or a ChannelGroup).
I'd like to provide a similar mechanism, but I don't understand how it work behind. For example, how can the function createSound() create a new istance of a Sound? The constructor is private and from the Sound interface there aren't any static methods or friendship. Are used some patterns?
EDIT: Just to make OP's question clear, s/he is not asking how to create a instance of class with private constructor, The question is in the link posted, how is instance of classes created which have private constructor and NO static methods or friend functions.
Thanks.
Hard to say without seeing the source code. Seems however that FMOD is 100% C with global variables and with a bad "OOP" C++ wrapper around it.
Given the absence of source code and a few of the bad tricks that are played in the .h files may be the code is compiled using a different header file and then just happens to work (even if it's clearly non-standard) with the compilers they are using.
My guess is that the real (unpublished) source code for the C++ wrapper is defining a static method or alternatively if everything is indeed just global then the object is not really even created and tricks are being played to fool C++ object system to think there is indeed an object. Apparently all dispatching is static so this (while not formally legal) can happen to work anyway with C++ implementations I know.
Whatever they did it's quite ugly and non-conforming from a C++ point of view.
They never create any instances! The factory function is right there in the header
/*
FMOD System factory functions.
*/
inline FMOD_RESULT System_Create(System **system)
{ return FMOD_System_Create((FMOD_SYSTEM **)system); }
The pointer you pass in to get a System object is immediately cast to a pointer to a C struct declared in the fmod.h header.
As it is a class without any data members who can tell the difference?
struct Foo {
enum Type {
ALPHA,
BETA_X,
BETA_Y
};
Type type () const;
static Foo alpha (int i) {return Foo (ALPHA, i);}
static Foo beta (int i) {return Foo (i<0 ? BETA_X : BETA_Y, i);}
private:
Foo (Type, int);
};
create_alpha could have been a free function declared friend but that's just polluting the namespace.
I'm afraid I can't access that link but another way could be a factory pattern. I'm guessing a bit, now.
It is the factory pattern - as their comment says.
/*
FMOD System factory functions.
*/
inline FMOD_RESULT System_Create(System **system) { return FMOD_System_Create((FMOD_SYSTEM **)system); }
It's difficult to say exactly what is happening as they don't publish the source for the FMOD_System_Create method.
The factory pattern is a mechanism for creating an object but the (sub)class produced depends on the parameters of the factory call. http://en.wikipedia.org/wiki/Factory_method_pattern

What to use instead of static variables

in a C++ program I need some helper constant objects that would be instantiated once, preferably when the program starts. Those objects would mostly be used within the same translation unit, so the simplest way to do this would be to make them static:
static const Helper h(params);
But then there is this static initialization order problem, so if Helper refers to some other statics (via params), this might lead to UB.
Another point is that I might eventually need to share this object between several units. If I just leave it static and put in a .h file, that would lead to multiple objects. I could avoid that by bothering with extern etc, but this can finally provoke the same initialization order issues (and not to say it looks very C-ish).
I thought about singletons, but that would be overkill due to the boilerplate code and inconvenient syntax (e.g. MySingleton::GetInstance().MyVar) - those objects are helpers, so they are supposed to simplify things, not to complicate them...
The same C++ FAQ mentions this option:
Fred& x()
{
static Fred* ans = new Fred();
return *ans;
}
Is this really used and considered a good thing? Should I do it this way, or would you suggest other alternatives? Thanks.
EDIT: I should have clarified why I actually need that helpers: they are very like normal constants, and could have been pre-calculated, but it is more convenient to do that at runtime. I would prefer to instantiate them before main, as it automatically resolves multi-threading issues (which local statics are not protected against in C++03). Also, as I said, they would often be limited to a translation unit, so it does not make sense to export them and initialize in main(). You can think of them as just constants but only known at runtime.
There are several possibilities for global state (whether mutable or not).
If you fear that you'll have an initialization issue, then you should use the local static approach to create your instance.
Note that the clunky singleton design you present is not mandatory design:
class Singleton
{
public:
static void DoSomething(int i)
{
Singleton& s = Instance();
// do something with i
}
private:
Singleton() {}
~Singleton() {}
static Singleton& Instance()
{
static Singleton S; // no dynamic allocation, it's unnecessary
return S;
}
};
// Invocation
Singleton::DoSomething(i);
Another design is somewhat similar, though I much prefer it because it makes transition to a non-global design much easier.
class Monoid
{
public:
Monoid()
{
static State S;
state = &s;
}
void doSomething(int i)
{
state->count += i;
}
private:
struct State
{
int count;
};
State* state;
};
// Use
Monoid m;
m.doSomething(1);
The net advantage here is that the "global-ness" of the state is hidden, it's an implementation details that clients need not worry about. Very useful for caches.
Let us, will you, question the design:
do you actually need to enforce the singularity ?
do you actually need the object be built before main starts ?
Singularity is generally over-emphasized. C++0x will help here, but even then, technically enforcing singularity rather than relying on programmers to behave themselves can be very annoying... for example when writing tests: do you really want to unload/reload your program between each unit test just to change the configuration between each one ? Ugh. Much more simple to instantiate it once and have faith in your fellow programmers... or the functional tests ;)
The second question is more technical, than functional. If you do need the configuration before the entry point of your program, then you can simply read it when it starts.
It may sound naive, but there is actually one issue with computing during the library load: how do you handle errors ? If you throw, the library is not loaded. If you do not throw and go on, you are in an invalid state. Not so funny, is it ? Things are much simpler once the real work has begun, because you can use the regular control-flow logic.
And if you think about testing whether the state is valid or not... why not simply building everything at the point where you'd test ?
Finally, the very issue with global is the hidden dependencies that are introduced. It's much better when dependencies are implicit to reason about the flow of execution, or the impacts of a refactoring.
EDIT:
Regarding initialization order issues: objects within a single translation unit are guaranteed to be initialized in the order they are defined.
Therefore, the following code is valid according to the standard:
static int foo() { return std::numeric_limits<int>::max() / 2; }
static int bar(int c) { return c*2; }
static int const x = foo();
static int const y = bar(x);
The initialization order is only an issue when referencing constants / variables defined in another translation unit. As such, static objects can naturally be expressed without issues as long as they only refer to static objects within the same translation unit.
Regarding the space issue: the as-if rule can do wonders here. Informally the as-if rule means that you specify a behavior and leave it up to the compiler/linker/runtime to provide it, without a care in the world for how it is provided. This is what actually enables optimizations.
Therefore, if the compiler chain can infer that the address of a constant is never taken, it may elide the constant altogether. If it can infer that several constants will always be equal, and once again that their address are never inspected, it may merge them together.
Yes, you can use Construct On First Use Idiom if it simplifies your problem. It's always better than global objects whose initialization depend on other global objects.
The other alternative is Singleton Pattern. Both can solve similar problem. But you've to decide which suits the situation better and fulfill your requirement.
To the best of my knowledge, there is nothing "better" than these two appproaches.
Singletons and global objects are often considered evil. The simplest and most flexible way is to instantiate the object in your main function and pass this object to other functions:
void doSomething(const Helper& h);
int main() {
const Parameters params(...);
const Helper h(params);
doSomething(h);
}
Another way is to make the helper functions non-members. Maybe they don't need any state at all, and if they do, you can pass a stateful object when you call them.
I think nothing speaks against the local static idiom mentioned in the FAQ. It is simple and should be thread-safe, and if the object isn't mutable, it should also be easily mockable and introduce no action at a distance.
Does Helper need to exist before main runs? If not, make a (set of?) global pointer variables initialized to 0. Then use main to populate them with the constant state in a definitive order. If you like you can even make helper functions that do the dereference for you.

C++ static initialization order

When I use static variables in C++, I often end up wanting to initialize one variable passing another to its constructor. In other words, I want to create static instances that depend on each other.
Within a single .cpp or .h file this is not a problem: the instances will be created in the order they are declared. However, when you want to initialize a static instance with an instance in another compilation unit, the order seems impossible to specify. The result is that, depending on the weather, it can happen that the instance that depends on another is constructed, and only afterwards the other instance is constructed. The result is that the first instance is initialized incorrectly.
Does anyone know how to ensure that static objects are created in the correct order? I have searched a long time for a solution, trying all of them (including the Schwarz Counter solution), but I begin to doubt there is one that really works.
One possibility is the trick with the static function member:
Type& globalObject()
{
static Type theOneAndOnlyInstance;
return theOneAndOnlyInstance;
}
Indeed, this does work. Regrettably, you have to write globalObject().MemberFunction(), instead of globalObject.MemberFunction(), resulting in somewhat confusing and inelegant client code.
Update: Thank you for your reactions. Regrettably, it indeed seems like I have answered my own question. I guess I'll have to learn to live with it...
You have answered your own question. Static initialization order is undefined, and the most elegant way around it (while still doing static initialization i.e. not refactoring it away completely) is to wrap the initialization in a function.
Read the C++ FAQ items starting from https://isocpp.org/wiki/faq/ctors#static-init-order
Maybe you should reconsider whether you need so many global static variables. While they can sometimes be useful, often it's much simpler to refactor them to a smaller local scope, especially if you find that some static variables depend on others.
But you're right, there's no way to ensure a particular order of initialization, and so if your heart is set on it, keeping the initialization in a function, like you mentioned, is probably the simplest way.
Most compilers (linkers) actually do support a (non-portable) way of specifying the order. For example, with visual studio you can use the init_seg pragma to arrange the initialization into several different groups. AFAIK there is no way to guarantee order WITHIN each group. Since this is non-portable you may want to consider if you can fix your design to not require it, but the option is out there.
Indeed, this does work. Regrettably, you have to write globalObject().MemberFunction(), instead of globalObject.MemberFunction(), resulting in somewhat confusing and inelegant client code.
But the most important thing is that it works, and that it is failure proof, ie. it is not easy to bypass the correct usage.
Program correctness should be your first priority. Also, IMHO, the () above is purely stylistic - ie. completely unimportant.
Depending on your platform, be careful of too much dynamic initialization. There is a relatively small amount of clean up that can take place for dynamic initializers (see here). You can solve this problem using a global object container that contains members different global objects. You therefore have:
Globals & getGlobals ()
{
static Globals cache;
return cache;
}
There is only one call to ~Globals() in order to clean up for all global objects in your program. In order to access a global you still have something like:
getGlobals().configuration.memberFunction ();
If you really wanted you could wrap this in a macro to save a tiny bit of typing using a macro:
#define GLOBAL(X) getGlobals().#X
GLOBAL(object).memberFunction ();
Although, this is just syntactic sugar on your initial solution.
dispite the age of this thread, I would like to propose the solution I've found.
As many have pointed out before of me, C++ doesn't provide any mechanism for static initialization ordering. What I propose is to encapsule each static member inside a static method of the class that in turn initialize the member and provide an access in an object-oriented fashion.
Let me give you an example, supposing we want to define the class named "Math" which, among the other members, contains "PI":
class Math {
public:
static const float Pi() {
static const float s_PI = 3.14f;
return s_PI;
}
}
s_PI will be initialized the first time Pi() method is invoked (in GCC). Be aware: the local objects with static storage have an implementation dependent lifecyle, for further detail check 6.7.4 in 2.
Static keyword, C++ Standard
Wrapping the static in a method will fix the order problem, but it isn't thread safe as others have pointed out but you can do this to also make it thread if that is a concern.
// File scope static pointer is thread safe and is initialized first.
static Type * theOneAndOnlyInstance = 0;
Type& globalObject()
{
if(theOneAndOnlyInstance == 0)
{
// Put mutex lock here for thread safety
theOneAndOnlyInstance = new Type();
}
return *theOneAndOnlyInstance;
}