我需要几个在程序运行时始终可用的独特对象。我遵循 Singleton 设计模式,它建议使用方法getInstance()
来获取对象。但我更喜欢立即检索对象而不调用方法。所以我写了一个类,它提供了几个由引用类型而不是指针返回的唯一对象。
class Priority
{
public:
static Priority &High;
static Priority &Medium;
static Priority &Low;
std::string getName(void);
int getLevel(void);
private:
Priority(int level, std::string const& name);
~Priority();
Priority(Priority const&);
const Priority &operator = (Priority const&);
int level_;
std::string name_;
};
Priority &Priority::High = Priority(3, "High");
Priority &Priority::Medium = Priority(2, "Medium");
Priority &Priority::Low = Priority(1, "Low");
Priority::Priority(int level, std::string const& name)
: level_(level), name_(name)
{ }
Priority::~Priority() { }
inline std::string Priority::getName(void)
{
return name_;
}
inline int Priority::getLevel(void)
{
return level_;
}
我编写了一个使用上述类的示例程序。
int main()
{
Priority &m = Priority::High;
std::string name = m.getName();
int level = m.getLevel();
return 0;
}
该程序运行良好。因此,我假设在
Priority &Priority::High = Priority(3, "High");
程序停止或存储类的 dll 文件被卸载之前,分配给变量的内存不会被清除。我对么?