[英]Where is a static local variable object of function defined?
I know that static member variables have to be defined out of the class somewhere (not in a header - in a TU), but I'm wondering then why the following works 我知道静态成员变量必须在类之外的某个地方定义(而不是在标头中-在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;
}
Where is the object associated with logger
defined? 与logger
关联的对象在哪里定义? And why doesn't a function static variable require a definition/instantiation point as for a static class member variable? 为什么函数静态变量不像静态类成员变量那样需要定义/实例化点?
You do define it: in the function GetInstance()
. 您确实定义了它:在函数GetInstance()
。
It's just that luck is on your side: that function is only encountered in exactly one translation unit (you've put the class definition in a source file), so the linker is not going to moan. 这只是运气就在你身边:该功能仅在只有一个翻译单位遇到的(你已经把类定义在源文件),因此链接器不会抱怨。
It would have been a different matter if the code were in a header and included in more than one translation unit. 如果代码位于标头中并且包含在多个翻译单元中,那将是另一回事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.