Question

I declared a global static pointer out of main function in main.cpp file. Do I need to initialize it in each cpp file it is used?

// main.cpp
...
static int *levels;
...
int main()
...

Then, if I have to initialize it in some other files rather than main.cpp, then what is the usage of global static variable? I can declare separate pointers in each cpp file.

Était-ce utile?

La solution 3

I would not generally advise to use singleton classes is good style, but here's what I would do:

MySingleton.hpp:


class MySingleton {
public:
    static MySingleton& instance() {
        static MySingleton theInstance;
        return theInstance;
    }
    std::vector<int>& levels() { return levels_; }

private:
    MySingleton() {
    }
    std::vector<int> levels_;
};

To use the above elsewhere:

#include "MySingleton.hpp"

// ...
MySingleton::instance().levels().resize(10); // Creates 10 ints initialized to 0

To shorten the access you could even wrap the whole thing in its own namespace and provide free functions there:

namespace MySpace {
    class MySingleton {
        // Blah, blah
    };

    std::vector& levels() {
        return MySingleton::instance().levels();
    }
}

and use it

MySpace::levels().resize(10);

Autres conseils

It depends on when you need it to be initialized.

If there are other static objects that need it:

static int * levels = new int[COMPILE_TIME_CONST];

is a good start. Be aware that static variables in a single compilation unit are initialized in the order that they appear in the source. The order of initialization in relation to statics in other compilation units is a much more complicated issue.

Definition: compilation unit is a single cpp file 
and the headers it includes directly or indirectly.

Fortunately you cannot access levels from any other compilation unit. [edit in response to comments]

If you don't need it until main has started then:

int main()
{
    levels = new int[someValueCalculatedInMain];
|

works.

An alternate solution that will allow access from multiple C++ files:

In a header file:

 int * getLevels(); 

In a cpp file:

int * getLevels()
{
   static int * levels = new int[calculatedArraySize];
   return levels;
}

Warning: This code is not thread-safe (before C++11 anyway). If your application uses multiple threads you need some additional code. This code also leaks the array when the program terminates. Normally this is not a problem but if it is there are solutions.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top