C ++:模板和单例模式 [英] C++: Templates and the singleton pattern

查看:83
本文介绍了C ++:模板和单例模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它发生了,所以我需要臭名昭著的单例模式.更好的是,它发生了,因此我需要结合该模式使用臭名昭著的C ++模板.所以,令我困扰的是:

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;
    }

    ...
};

这是实现应该在首次使用时创建的单例的典型方法.现在,这里有一个静态变量 singleton .由于 instance()函数可以从几个不同的模块中调用,因此问题是:对于任何给定的 T 类型,该对象将只有一个实例,还是每个模块实例化自己的单例吗?

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?

推荐答案

每种类型 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.

这篇关于C ++:模板和单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆