gpt4 book ai didi

c++ - 初始化单例的const成员变量

转载 作者:行者123 更新时间:2023-11-28 06:19:08 29 4
gpt4 key购买 nike

这是我尝试做的(因为问题的标题可能无法很好地描述整个问题)。

在我想编写的程序中,我需要动态创建存储在 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com