• Advertisement
Sign in to follow this  

How do I implement the singleton I describe without circular inclusion?

This topic is 1566 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a class called 'Window' which essentially contains everything need to run my program.  Inside window, I have 'Simulation', 'Renderer' and 'InputController' classes.  In some instances, these classes need access to a global pointer to a 'Window'.  For example:  I have a DrawDebug() function in 'Renderer' which needs to get information about the status of the Simulation so it can be drawn as text on screen.  I'm not sure exactly how to go about doing this and some help would be much appreciated.  Thanks :)

Share this post


Link to post
Share on other sites
Advertisement

Why not just have this

 

 

 
// A function to get access to the singleton at anytime so there is no need for any parameters for the Window class
class Window
{
public:
    static Window* getInstance()
    {
        static Window instance;
        return &instance;
 
    }
};
 
// You can also do it with dynamic memory instead of a static instance, which is preferred.

Share this post


Link to post
Share on other sites

Because few people would consider a window to be a good candidate for singleton usage.

Share this post


Link to post
Share on other sites

Yes, that looks so wrong. The window would be created at a totally random time or even never if noone asks for the pointer.

And later someone wants two windows...

Share this post


Link to post
Share on other sites

Programming is much about keeping the number of dependencies as low as possible. With many dependencies, the source code is difficult to modify. When you find yourself in the situation that you have cyclic dependencies of header files, it is a sign that you may be doing something wrong. Of course, there are valid use cases, but I try to avoid them.

 

In worst case, using header guards, recursion can be avoided at the cost of strange compilation errors.

 

The use of forward declaration may solve this. It is actually a good general principle. Use it wherever possible, so as to avoid including header files.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement