更新时间:2023-11-15 12:35:22
我通常不建议使用singleton类是好的风格,我会做什么:
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();
}
}
并使用
MySpace::levels().resize(10);