C /此和静态类名称之间的差异

c++ / difference between this and static class name

本文关键字:之间 静态类      更新时间:2023-10-16

一个问题

一个问题
Cl& Cl::getInstance()
{
    static Cl instance;
    return instance;
}

我通过此代码实现了什么,如果我返回this

*此方法是静态

如果该方法是静态的,则未隐式定义this,因此问题不适用。

另一方面,如果该方法是非静态成员,则有很大的区别。

Cl& Cl::getInstance()
{
    static Cl instance;
    return instance;
}

在这里,您总是返回同一实例,甚至从同一类的几个实例中调用:a singleton (误导返回的实例与呼叫者实例无关)

Cl& Cl::getInstance()
{
    return *this;
}

上面,您正在返回当前实例(不是很感兴趣...)

编辑:也许您的问题与单顿设计模式有关,因为构造函数是私有的,没有对象可以在不使用 getInstance()的情况下获得有效的 Cl对象,在这种情况下,兴趣是它返回每个呼叫者的实例:

Cl& Cl::getInstance()   // static method
{
    static Cl instance;  // constructor is private, only can be called from here
    return instance;
}