在实践中,单例模式是使用返回一个局部静态变量的简单静态函数创建的。只要实例是静态的,它就会返回在第一次函数调用期间定义的相同变量。
对我来说令人困惑的部分是,如果我在一个头文件中声明带有静态局部变量的普通静态函数,并在调用该函数时将该头包含在两个不同的翻译单元中,则函数局部静态变量将被构造两次 - 每个翻译单元都构造。
原因是静态函数标识符函数链接是内部的,因此每个翻译单元(源文件)都有该函数的两个实例,因此该静态变量有两个本地实例。
我的问题是为什么同样的逻辑不适用于单例模式?当我们声明静态函数时,为什么它没有内部链接,因此为什么不创建局部静态变量的两个实例(根据定义,它是唯一的单例实例)?
我正在谈论的单例主要功能:
static className& instance() { static className instance; return instance; }