I have a Singleton class:
// in global space
TNCManager *TNCManager::_globalInstance = new TNCManager();
Why is the constructor of TNCManager
executed before the main()
function?
I have a Singleton class:
// in global space
TNCManager *TNCManager::_globalInstance = new TNCManager();
Why is the constructor of TNCManager
executed before the main()
function?
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.
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.