-1

I have a Singleton class:

// in global space
TNCManager *TNCManager::_globalInstance = new TNCManager();

Why is the constructor of TNCManager executed before the main() function?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 2
    Short answer: because this is behavior specified in the standard. Long answer: get rid of it. – SergeyA Jan 31 '17 at 21:35
  • 1
    Since it's global, it has to be fully constructed before `main` begins. If it wasn't how could you use it? If it happened sometime during `main` (maybe handled by a different thread), how would you know if it was constructed or not? If it happened after `main`, the program would be over. – Kevin Jan 31 '17 at 21:35
  • 2
    Check http://stackoverflow.com/questions/1008019/c-singleton-design-pattern for the idiomatic way and lazy construction. – πάντα ῥεῖ Jan 31 '17 at 21:35
  • 2
    When did you expect it to be performed? – Lightness Races in Orbit Jan 31 '17 at 21:36
  • @Kevin: That's not _quite_ true. It's required to be fully constructed before any code in that code unit (cpp file) gets executed. The assumption that it's before main is a common cause of bugs :( – Mooing Duck Jan 31 '17 at 21:40

2 Answers2

2

Why does constructor of TNCManager perform before main() function?

All of the global statically allocated objects will be instantiated before main() executes. Hence the constructor is called with new TNCManager().

The idiomatic way, that avoids the construction before any access (lazy instantiation) is to write:

// in class space
class TNCManager {
public:
    TNCManager& instance() {
        static TNCManager theInstance;
        return theInstance;
    }
    // ...
};

See more details explained here.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
-1

Practically, because main () might, and should be able to, use TCNManager. The way applications work is to allocate memory, load the code and data, initialize storage and then call _main (). Before C++, initializing the data simply involved copying the initial data to the storage location. With classes, this involves calling the constructor.

Mike
  • 2,721
  • 1
  • 15
  • 20