【发布时间】:2013-09-25 05:54:30
【问题描述】:
最近我阅读了一些 C++ 代码,大量使用了 getInstance() 方法:
class S
{
private:
int some_int = 0;
public:
static S& getInstance()
{
static S instance; / (*) /
return instance;
}
};
从这段代码的使用方式中,我了解到 getInstance() 的工作方式类似于return this,返回class S 实例的地址(或引用)。但我很困惑。
1) line(*) 中定义的静态变量S 在内存中分配在哪里?为什么它可以像return this 一样工作?
2) 如果class S 存在多个实例,会返回谁的引用?
【问题讨论】: