问题描述:

Is there a way to call a function in init list with no context of data memeber?

For example this:

class x{

public:

x(char ch): ..., foo() {} // doesn't work

...

void foo(); //foo sets the keys in keys[], different keys for different ch

private:

char keys[10];

}

instead of this:

class x{

public:

x(char ch): ... {(ch == 'a') ? foo("asdfg..."): foo("qwert..") ;}

...

void foo();

private:

char keys[10];

}

Does the init list syntax always have to be {data member name}(value)?

Also, I read that it's preferable to use init list instead of the constructor's function because this way it doesn't make a copy, but in this case does it matter?

网友答案:

Is there a way to call a member function in init list?

Yes.

But the result of an expression in the member initialization list must always be assigned to a member variable, so calling a void function in the member initialization list is going to need some hackery. It's possible but pointless, because the call could be just as well done in the constructor body.

What would make more sense in a member initialization list, is to call a function that returns a value that would be copied to the member. You cannot return raw arrays though, so that's not an opion unless you change the type of keys.

Also, I read that it's preferable to use init list instead of the constructor's function because this way it doesn't make a copy, but in this case does it matter?

It's true that copy-initializing a member in the member initialization list allows the copy to be elided while copy-assigning in the constructor body does not. That includes copying the return value of a function that's called in the member initialization list, but it does not apply to any copy-assignments done inside the function. You've misunderstood how the use of member initialization list can avoid copying.


Now, default initializing and copying an array 10 characters is not a lot of work. But you can minimize the amount of copying by using aggregate initialization. For that, x would have to be an aggregate. There is already an aggregate that wraps an array in the standard library since c++11: std::array. I recommend that you use that instead of x. You can write a function that returns the desired array based on the parameter.

相关阅读:
Top