- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我尝试做的(因为问题的标题可能无法很好地描述整个问题)。
在我想编写的程序中,我需要动态创建存储在 vector 列表中的对象的实例。
class A {...};
int main()
{
std::vector<A *> as;
as.push_back(new A);
as.push_back(new A);
...
return 0;
}
一旦 vector 被“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() 中声明的 vector 列表传递给单例,并确保单例中的“as”不再是可修改的(因此是 const)。
这样做的原因是因为我希望 Singleton 继续重用 vector 列表 (Singleton::as) 中的对象,但我想确保在程序中的任何时候,这个列表都会被修改一次正在使用单例。
我尽力描述了我想做的事情。也许有一种模式可以做到这一点。我不知道这个设计是否有意义,或者更重要的是我看不到如何实现这样的东西(我似乎找不到在使用单例之前初始化 Singleton 的 const 成员变量的方法 - 看起来违背了 Singleton 本身的概念,因为 static Singleton instance
将在程序运行时立即创建)。
如果我以某种方式不在 main() 中声明 std::vector 而是声明为全局变量,这似乎是可能的,但我想尽可能避免使用全局变量。
欢迎任何建议、帮助和想法。
最佳答案
您可以使用辅助方法在构造函数中初始化 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()){}
关于c++ - 初始化单例的const成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29610179/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!