How to declare a static instance of a class in C ++?

A few months ago, I created a C # project for a game called Vexed. Now I am creating Tetris, but in C ++. Basically, I want to use the same logic as in another project, it was a bit like:

I created a class called "Game", where there was all the information about the game. He had methods, variables and all that. Then I created a static class called "PublicInstances" or something like that, and in this class I said something like this:

static class PublicInstances
{
    public static Game vexedGame = new Game(); //This is C# and works.
}

This made it so easy to use, because any change I made to the game was saved in a static instance of my class, and I could access it anywhere in the project. I want to know exactly how to do this with C ++ in order to create a public or global instance of my class game so that I can access it and change it everywhere and update everything in any form or class of my project. I would really appreciate your help.

// Sorry if my english is not the best ^^

+4
source share
1 answer

Repetition and generalization

Option 1

You can simply declare and define a global instance of the Game object. In the header file, for example. game.h:

extern Game globalGameObj;

game.h , globalGameObj . . , . game.cc( ):

Game globalGameObj;

:

globalGameObj.do_some_work();

2

, singleton. Game (game.h) :

class Game
{
  public:
    static Game &shared_instance() {static Game game; return game;}

  private:
    // Make constructor private. Only shared_instance() method will create an instance.
    Game() {/*whatever initialisation you need*/}
};

shared_instance():

Game::shared_instance().go_some_work();

, static class PublicInstances. ++ (, PublicInstances), , , , . , , , , .

? , . , . 1 2 : , . , singleton - , . , , .

:)

2 , Game, .

static Game *instance() {if (!_inst) _inst = new Game(); return _inst;}

, , Kal, argiopeweb Simple. ++ 03 . ++ 11 .

++ 11 draft, secion 6.7

such a variable is initialized the first time control passes through its declaration;
such a variable is considered initialized upon the completion of its initialization. [...]
If control enters the declaration concurrently while the variable is being initialized,
the concurrent execution shall wait for completion of the initialization.
+3

All Articles