Is there any problem of calling functions in the initialization list?
I'm writing this copy constructor:
//CCtor of RegMatrix
RegMatrix::RegMatrix(const RegMatrix &other){
this-> numRow = other.getRow();
this-> numCol = other.getCol();
//Create
_matrix = createMatrix(other.numRow,other.numCol);
int i,j;
//Copy Matrix
for(i=0;i<numRow; ++i){
for(j=0;j<numCol; ++j){
_matrix[i][j] = other._matrix[i][j];
}
}
}
Is there a problem to initialize numRow, numCol i开发者_StackOverflow中文版n the initialization list like this: numRow(other.numRow), numCol(other.numCol)
instead of:
this-> numRow = other.getRow();
this-> numCol = other.getCol();
Also, i don't know if there isn't such a problem, is there a problem of calling other classes' object's function in the initialization list, such as:
numRow(other.getRow())
instead of:
this-> numRow = other.getRow();
Is there a problem to initialize numRow, numCol in the initialization list [...]?
In general, there's two problems with doing so:
- While initializing objects in the initialization list, the object is not yet fully constructed. Therefore, when you're invoking non-static member functions, you are invoking them on a not yet fully constructed object. If those functions attempt to use any sub-object of the object that has not been constructed, you are invoking Undefined Behavior.
- The order of initialization is the order of declaration of the members in the class definition, it is not the order in which they are listed in the initialization list. Therefore you need to pay attention to initialization of members requiring data from other members. (This can be seen as a sub-problem of the previous: using not yet constructed sub-objects.) It is best to avoid such situations, but if they cannot be avoided, add a big, scary comment to where the members are declared in the class' definition, emphasizing the importance of their order.
In your concrete example this doesn't matter, so you are safe to do this.
No there is no problem actually. Except that be careful that the order of initialization is NOT the order in which you specify initializers in the init-list. The order is the one in which your members have been declared in the class. Other than that potential problem, I see none. HTH
精彩评论