C /此和静态类名称之间的差异
c++ / difference between this and static class name
一个问题
一个问题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;
}
相关文章:
- 在C++中使用非静态类函数的函数
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- 在C++中,为什么使用静态类函数而不是常规函数?
- 静态类属性,C++中的多个构造函数
- 如何从静态类函数初始化静态类对象
- 在 c++ 中使用字符串变量选择静态类结构,而不带对象
- 是否通过单元化指针UB访问静态类成员
- 如何在 c++ 中初始化静态类对象?
- 为静态类创建指向对象的指针是否合法?
- thread_local静态类在程序退出时在无效地址处销毁
- 从静态成员函数访问私有非静态类变量 - C++
- 在子类中填充静态类成员
- 静态类变量的多重定义
- 作为成员的静态类模板实例会导致未解析的外部符号错误
- uninit_member:非静态类成员字段 m_cJobState.bstatus 未在此构造函数中初始化,也不在其调
- uninit_member:非静态类成员m_wszParams未在此构造函数中初始化,也不在它C++中调用的任何函数中初
- 使用静态类成员而不是私有字段之间的速度差异是什么?
- C /此和静态类名称之间的差异
- 静态类在其他类之间不显示相同的值
- 在实例之间共享类变量而不使用静态