简体   繁体   中英

C++ Constructors and static members

I was trying something out and i don't know what is going on with the code. I have a class which has a static member and the default constructor and an overloaded one.

class Remote
{
public:
    static std::vector<Remote*> channels;

    static void interrupt() {
        for (Remote* r : channels) {
            r->ProcessInterrupt();
        };
    }

    void ProcessInterrupt() {
        std::cout << "ProcessInterrupt called.";
    };

    Remote(const int a) {
        std::cout << "Remote(const int a) called.\n";
        channels.push_back(this);
    }
    Remote() {
        Remote(1);
        std::cout << "Remote() called.\n";
    }
    ~Remote() {
        std::vector<Remote *>::iterator ch = std::find(channels.begin(), channels.end(), this);
        if (ch != channels.end()) {
            channels.erase(ch);
        };
    }
};

In main.cpp i declare two instances of the class Remote. What i now notice is that if i instantiate them with the default constructor the pointers are not added to the vector. Then i tried using the overloaded constructor and it does add it to the vector.

Remote r1 = Remote();
Remote r2 = Remote(1);
std::cout << Remote::channels.size() << "\n";
Remote::interrupt();

I would expect that since i'm calling the overloaded constructor it would still add the pointer to the vector. This, however, is clearly not happening.

Could anyone explain what is happening?

Kind regards,

Bob

The constructor

Remote() {
    Remote(1);
    std::cout << "Remote() called.\n";
}

Doesn't add anything to the channels vector. Remote(1) in this context , is not a delegating constructor.

Try this instead:

Remote() : Remote(1) {
    std::cout << "Remote() called.\n";
}

See an example here: https://ideone.com/ahauPV

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