C++:模板和单例模式
碰巧我需要臭名昭著的单例模式。更好的是,它发生了,所以我需要臭名昭著的 C++ 模板与该模式的结合。所以,令我困扰的是:
template <class T>
class PDatabaseTable
{
...
static PDatabaseTable <T> & instance()
{
static PDatabaseTable <T> singleton;
return singleton;
}
...
};
这是实现单例的典型方法,该单例应该在第一次使用时创建。现在,我们有一个静态变量singleton。由于 instance() 函数可能会从多个不同的模块调用,因此问题是:对于任何给定类型 T 是否只有一个对象实例,还是每个模块实例化它自己的单例?
It happens so that I have a need of the infamous singleton pattern. Better yet, it happens so that I have a need of infamous C++ templates in combination with that pattern. So, what troubles me is this:
template <class T>
class PDatabaseTable
{
...
static PDatabaseTable <T> & instance()
{
static PDatabaseTable <T> singleton;
return singleton;
}
...
};
This is a typical way to implement a singleton that's supposed to be created on the first use. Now, here we have a static variable singleton. Since the instance() function may be called from several different modules, the question is: will there be only one instance of the object for any given type T, or will every module instantiate its very own singleton?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每种类型
T
都只有一个实例,就像如果它不是模板,就只有一个实例一样。该函数是内联的,这意味着虽然它可以在多个编译单元中定义,但链接后将只有一个版本,并且任何本地静态对象都只有一个实例。
There will only be one instance for each type
T
, just as, if it weren't a template, there would only be one instance.The function is inline, meaning that although it can be defined in multiple compilation units, after linking there will be only one version of it, and only one instance of any local static objects.
您的单例称为 Meyers Singleton,您可以在 G++ 中的静态局部变量和线程安全 文章很好地解释了静态局部变量如何线程安全地创建。
Your singleton is called Meyers Singleton and you can find an explanation about thread safety of this singleton type in Static locals and threadsafety in g++ article which nicely explains how static local variables are thread-safe to create.
肯定会有只有一个实例。
我只是想知道为什么不能将静态对象从函数中移到类主体中?
Definitely there will be only one instance.
I am just wondering why can't you move that static object out of function to the class body ?
您可以将 static 的 init 移到类体之外,这对于 static 函数也是可能的。
You CAN move the init of the static outside of the class body, and this is also possible for the static function.