C++ class initializing list and passing functions

2019-06-14 19:20发布

问题:

I really searched the web for this but never came up with an answer. I know two ways of initializing a class and one of them doesn't work when I try to pass a function. Can you help me understand why this happens? And what method should I use? Thanks in advance!

void func(int i){
    cout << "GG " << i; 
}

class ac{
public:
    int a;
    function<void()> sh = bind(&func, a);

    /*ac (int i){   This does not work
        a = i;
    }*/

    ac (int i) : a(i) {};   // but this does

    void go (){
        sh();
    }
};

int main() {
    ac ac1(5);
    ac1.go();
    return 0;
}

Edit: Thanks for all the responses, this was a lot quicker than I thought. It seems like the output of the first example was some random garbage, I wasn't sure that's why I hesitated to detail the output.

回答1:

ac (int i){
    a = i;
}

Does not work since sh is initialized using an uninitialized value of a.



回答2:

Binding happens when you call bind.

And bind happens in constructor initialization list.

So in your code, when your bind the function, you bind it with current value of a - which is random unless it was inititalized in constructor initialization list.



回答3:

When you do in class initialization it is just a short hand to have that done by the constructor if you do not do it yourself. That means

ac (int i){
    a = i;
}

Becomes

ac (int i) : a(garbage), sh(bind(&func, a)){
    a = i;
}

So now we have a default initialized (which in this case means it contains garbage) a being used for the function so we have garbage. The reason a comes before sh is that is the way the declred in the class and that dictates the order of initialization.

The second example works as the constructor is treated as

ac (int i) : a(i), sh(bind(&func, a)){
    a = i;
}

And now when we bind a to func a is initialized to an actual value.