[英]Initializing const member variables of a singleton
这是我尝试做的事情(因为问题的标题可能无法很好地描述整个问题)。
在我要编写的程序中,我需要动态创建存储在矢量列表中的对象的实例。
class A {...};
int main()
{
std::vector<A *> as;
as.push_back(new A);
as.push_back(new A);
...
return 0;
}
一旦向量已被“ As”填充,我想将其“传递”到单例对象。
class Singleton
{
private:
Singleton() {}
// set this with the content of ::as created in main?
const std::vector<A*> as;
public:
Singleton& instance()
{
// how can I set 'as' before the instance is returned/even created?
static Singleton instance; return instance;
}
};
...
int main(...)
{
std::vector<A *> as;
as.push_back(new A);
as.push_back(new A);
...
// I'd like Singleton::as to be set with the content of 'as'
// before I use the singleton for the first time?
Singleton::instance.doSomethingWithAs();
return 0;
}
理想情况下,我想找到一种将main()中声明的向量列表传递给单例的方法,并确保单例中的“ as”不再可修改(因此为const)。
这样做的原因是因为我想让Singleton继续重用向量列表(Singleton :: as)中的对象,但是我想确保在程序中的任何时候,一旦Singleton被修改,此列表就不会被修改。正在使用。
我尽力描述了我想做什么。 也许有这样做的模式。 我不知道这种设计是否有意义,或更重要的是我看不到如何实现这样的功能(在使用单例之前,我似乎无法找到初始化Singleton的const成员变量的方法-似乎违背Singleton本身的概念,因为将在程序运行后立即创建static Singleton instance
)。
如果我不以main()声明std :: vector而不是在main()中声明它为全局变量,则似乎是可能的,但我想避免使用全局变量(如果可能)。
任何建议,帮助,想法都将受到欢迎。
您可以使用辅助方法初始化构造函数中的const成员:
std::vector<A*> make_as()
{
std::vector<A*> as;
as.push_back(new A);
as.push_back(new A);
//..
return as;
}
Singleton::Singleton() : as(make_as()){}
您可以在instance
方法参数as
作为指针传递,该参数的默认值为nullptr
,如下所示:
请注意,我将instance
方法更改为static
方法。 我不知道这是否是一个好的设计,我从未使用过这样的代码。
class A {};
class Singleton
{
private:
Singleton(std::vector<A *>* p) : as(*p) {}
// set this with the content of ::as created in main?
const std::vector<A*> as;
public:
static Singleton& instance(std::vector<A *>* p=nullptr)
{
// how can I set 'as' before the instance is returned/even created?
static Singleton instance(p); return instance;
}
void useMe() {
}
};
int main()
{
std::vector<A *> as;
as.push_back(new A);
as.push_back(new A);
Singleton::instance(&as);
Singleton::instance().useMe();
}
为了初始化对象的const
成员, 必须在构造函数的初始化列表中进行操作。 这意味着您被迫使其成为instance
函数的一部分。 您可以对此进行分层,以便instance
不使用参数,而是调用create_instance
。
Singleton(const vector<A*> * init) : as(*init)
{
}
Singleton& create_instance(const vector<A*> * init)
{
static Singleton instance(init);
return instance;
}
Singleton& instance()
{
return create_instance(null_ptr);
}
为了完整性,您应该进行一些错误检查,如果使用非null参数多次调用create_instance
则会引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.