问题描述:

I have an object that needs to be "global" in a sense that I need to be able and access it from within my other classes .h and .cpp files. I'm not sure how to approach this so let me describe the issue in more detail.

I have a class called CoreEnvironment. This class holds the core of my engine at it's lowest level such as: Rendering, Networking, Physics, and PathFinding. There is only ever one instance of this class that can exist at a time and it exists for the entire lifetime of the application. My first thoughts were to create it as a Singleton but after doing research there is a lot of negative comments about using singletons nor do I fully understand how to create one. In my research I saw use of the "Extern" keyword however I was unclear on it's usage.

Here is a skeleton of the class:

class CoreEnvironment

{

NetHandler* m_NET;

NetPoint* Server;

PhysicsHandler* m_Physics;

irr::IrrlichtDevice* Device;

irr::ITimer* Timer;

public:

CoreEnvironment();

~CoreEnvironment();

bool RunDevice();

void Update();

} CoreEnv;

I have some higher level classes in my engine such as: ActorHandler and WorldHandler. Inside the .cpp files for these two classes I need access to CoreEnv. If I simply #include "CoreEnvironment.h" another instance of CoreEnv is created each time the file is included, but I need access to the original one that was initialized.

This whole structure may be the incorrect approach. Any tips or suggestions to remedy this problem or to a more efficient approach is greatly appreciated. Thank you for your time.

网友答案:

Don't define the object instance within the header file. Provide a declaration there and define the object in a single cpp file. For instance,

CoreEnvironment.h

class CoreEnvironment
{
    NetHandler* m_NET;
    NetPoint* Server;
    PhysicsHandler* m_Physics;
    irr::IrrlichtDevice* Device;
    irr::ITimer* Timer;

public:
    CoreEnvironment();
    ~CoreEnvironment();

    bool RunDevice();
    void Update();
};

extern CoreEnvironment CoreEnv;

CoreEnvironment.cpp

#include "CoreEnvironment.h"

CoreEnvironment CoreEnv;

And if there are only two other classes that require access to the CoreEnv object, maybe you should rethink the need for the global instance. Instead something like this might suffice.

int main()
{
    CoreEnvirnment CoreEnv;
    ActorHandler actor(CoreEnv); 
    WorldHandler world(CoreEnv);

    // do stuff with actor and world
}

where the constructors of ActorHandler and WorldHandler take (maybe const) references to CoreEnvironment.

相关阅读:
Top