gpt4 book ai didi

c++ - C++ 中的单例习语

转载 作者:行者123 更新时间:2023-11-27 23:50:51 26 4
gpt4 key购买 nike

我想将代码从自定义语言转换为 C++。对于单例模式,我看到至少有 2 种简单的翻译方法。

1:

namespace Singleton 
{
int a, b;
int Function()
{
return a+b;
}
}

int test = Singleton::Function();

2:

struct Singleton 
{
int a, b;
int Function()
{
return a+b;
}
} Singleton; //<-- The only instance

int test = Singleton.Function();

我知道从概念上讲它们是等价的。我不是在寻找针对实例化/定义分离的封装/保障措施,因为这是转译,所以我不关心美学甚至代码长度。

但我想知道:这些是否会始终严格生成相同的程序集?我确实更喜欢第二个,因为在结构中我可以声明以我想要的任何顺序相互引用的方法:

struct Singleton 
{
int a, b;
int Function2()
{
return Function() + 1;
}
int Function()
{
return a+b;
}
} Singleton;

int test = Singleton.Function2();

而如果我使用命名空间,Function() 应该是未声明的标识符。

那么,我是否有任何实际理由要转译成命名空间?编译器完成后,结构的单个实例是否始终或完全具有相同的含义?

最佳答案

它们几乎肯定不会生成相同的程序集。在命名空间的情况下,Function 采用零参数并访问两个全局变量;在 struct 的情况下,Function 接受一个隐藏的 this 指针并通过它引用两个变量。

然而,性能差异不太可能会产生影响,因此程序集是否相同并不重要。

真正的问题是你是否想在两个翻译单元(.cpp 文件)之间共享这个单例。如果你这样做,我会更喜欢 namespace 版本,因为语言保证只有一个,而使用结构,你可能会不小心编写 struct Singleton Singleton2; 并最终得到两个。

如果单例对于单个 .CPP 是本地的,那么您不需要命名该结构:

struct // nameless struct.
{
int a, b;
int Function()
{
return a+b;
}
} Singleton; //<-- The only instance

int test = Singleton.Function();

最后的想法:还有另一个选项(几乎与命名空间选项相同):

struct Singleton 
{
static int a, b; // All members must be static.
static int Function()
{
return a+b;
}
Singleton() = delete; // Prevent creating any instances.
};
Singleton::a; // Must define the static members.
Singleton::b;


int test = Singleton::Function();

这允许以任意顺序声明函数,并且可以在文件之间共享。

关于c++ - C++ 中的单例习语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46586191/

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