[英]Manipulate a local static pointer variable outside the function where it is defined
[英]Where is a static local variable object of function defined?
我知道靜態成員變量必須在類之外的某個地方定義(而不是在標頭中-在TU中),但是我想知道為什么下面的方法可行
#include <iostream>
class Logger {
public:
static const Logger& GetInstance() {
static Logger logger; // ??
return logger;
}
void hello() const {
std::cout << "Hello";
}
private:
Logger() {
}
};
const Logger& logger = Logger::GetInstance();
int main(int argc, char* argv[]) {
logger.hello();
return 0;
}
與logger
關聯的對象在哪里定義? 為什么函數靜態變量不像靜態類成員變量那樣需要定義/實例化點?
您確實定義了它:在函數GetInstance()
。
這只是運氣就在你身邊:該功能僅在只有一個翻譯單位遇到的(你已經把類定義在源文件),因此鏈接器不會抱怨。
如果代碼位於標頭中並且包含在多個翻譯單元中,那將是另一回事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.