我有counter.h:
static int count() {
static int counter = 0; // called anew in each translation unit
return ++counter;
}
Run Code Online (Sandbox Code Playgroud)
和Singleton.h:
class Singleton
{
public:
Singleton(const Singleton& other) = delete;
Singleton& operator = (const Singleton& other) = delete;
static Singleton& instance()
{
static Singleton ret; // called only once
return ret;
}
private:
Singleton() { std::cout << "call\n"; }
};
Run Code Online (Sandbox Code Playgroud)
和foo.cpp:
void foo()
{
count();
auto& db = Singleton::instance();
}
Run Code Online (Sandbox Code Playgroud)
动物园.cpp:
void zoo()
{
count();
auto& db = Singleton::instance();
}
Run Code Online (Sandbox Code Playgroud)
主要.cpp:
int main()
{
foo();
zoo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么线路static int counter = 0;打了两次但只打了static Singleton ret;一次?
该函数int count()被声明static,因此它获得内部链接,这意味着在使用该函数的每个翻译单元中都会创建该函数的单独副本。
如果您想在应用程序中使用单个count()函数,请不要声明它static,以便它获得外部链接(并将定义移至 .cpp 文件),或者只是声明它inline。
inline int count() {
static int counter = 0;
return counter;
}
Run Code Online (Sandbox Code Playgroud)
这与班级成员不同static。类成员(包括static类成员)获得与其所属类相同的链接(在您的情况下具有外部链接)。