getInstance()如何工作? [英] How does getInstance() work?

查看:93
本文介绍了getInstance()如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我使用广泛的getInstance()方法读取了一些C ++代码:

Recent I read some C++ code using extensively following getInstance() method:

class S
{
    private:
        int some_int = 0;
    public:
        static S& getInstance()
        {
            static S instance; / (*) /
            return instance;
        }
};

从这个代码片段的使用方式,我学习了getInstance > return this ,返回类S 的实例的地址(或引用)。但是我感到困惑。

From how this code fragment being used, I learned the getInstance() works like return this, returning the address(or ref) of the instance of class S. But I got confused.

1)在内存中分配的行(*)中定义的静态变量 S ?为什么它可以工作返回这个

1) where does the static variable S defined in line(*) allocated in memory? And why it can work like return this?

2)如果存在多个<$

2) what if there exist more than one instance of class S, whose reference will be returned?

推荐答案

这是所谓的称为 设计模式。它的区别特征是,只能存在该类的正好一个实例,并且模式确保。该类有一个私有构造函数和一个静态创建的实例,与 getInstance 方法一起返回。

This is the so-called Singleton design pattern. Its distinguishing feature is that there can only ever be exactly one instance of that class and the pattern ensures that. The class has a private constructor and a statically-created instance that is returned with the getInstance method. You cannot create an instance from the outside and thus get the object only through said method.

由于实例

这篇关于getInstance()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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