简体   繁体   中英

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

#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? 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() .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM