The usage of global static pointer with multiple initialize?

痴心易碎 提交于 2019-12-25 07:33:17

问题


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.


回答1:


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);



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/23301727/the-usage-of-global-static-pointer-with-multiple-initialize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!