简体   繁体   中英

private Load() method for classes, how do they work

I'm pretty new to c++ and I have run into some code I am having trouble with, hopefully someone can enlighten me. It's what I understand to be a singleton class, it's used to hold the settings for an application. The class has a private constructor, and a private Load() method. It also instantiates itself as a private member which all seems ok I guess.

private:
MySettings(void);
MySettings(const MySettings&);
static MySettings& GetInstance();

bool Load();

private:        
    static MySettings mySettings;

The code within the class's Load() method seems to be executing however, and I dont understand why. I'm not (can't?) calling it anywhere in my app. Is the fact the method name is "load" of any special significance? I haven't seen any c++ guides that have talked about a speical "load" method for classes.

If someone could point my in the right direction id appreciate it, thanks

The only method that has special significance is the main function, which gets called automatically when you start the program. Load however, has no special significance. Its purpose is to avoid the loading the data when constructing the object, just in case it gets passed around everywhere (and all the copies would end up loading the data over and over).

In short, no. It has no special significance. You have to be calling it somewhere . Since it's private, you should check your constructor. It's probably calling Load.

There's nothing special about a method named Load . If you think it's getting executed, it got called explicitly somewhere. Either it got called from another method of your class, or the class makes another class or method friends, and that other entity makes the call.

The key is this:

private:
    static MySettings mySettings;

This is declaring a static instance of MySettings. Static instances are constructed before main() runs. (So the constructor is invoked then.)

Somewhere in a.cc file, you will find something like this:

MySettings MySettings:mySettings;

...which is the definition that goes with the declaration.

Actually, this is a somewhat clever way of creating a singleton.

(Update: I am guessing the constructor calls Load().)

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