在初始化列表中调用函数有什么问题吗? [英] Is there any problem of calling functions in the initialization list?
问题描述
我正在写这个拷贝构造函数:
// Regtorat的CCtor
RegMatrix :: RegMatrix RegMatrix& other){
this-> numRow = other.getRow();
this-> numCol = other.getCol();
//创建
_matrix = createMatrix(other.numRow,other.numCol);
int i,j;
//复制矩阵
for(i = 0; i for(j = 0; j _matrix [i] [j] = other._matrix [i] [j];
}
}
}
numRow,numCol在初始化列表中像这样: numRow(other.numRow),numCol(other.numCol)
而不是:
this-> numRow = other.getRow();
this-> numCol = other.getCol();
此外,我不知道是否没有这样的问题,是有问题的在初始化列表中调用其他类的对象的函数,例如:
numRow(other.getRow())
而不是:
this-> numRow = other.getRow();
在初始化列表中初始化numRow,numCol [...]
,这样做有两个问题:
- 在初始化列表中初始化对象时,对象尚未完全构建。因此,当您调用非静态成员函数时,您正在 尚未完全构造的对象 上调用它们。如果这些函数尝试使用尚未构建的对象的任何子对象,则您正在调用 未定义的行为。
- 初始化顺序是 在类定义 中声明成员的顺序, 不是 在初始化列表中列出的顺序。因此,您需要注意需要来自其他成员的数据的成员的初始化。 (这可以被看作是前面的子问题:使用尚未构造的子对象。)最好避免这种情况,但如果它们不能被避免,则对成员声明的地方添加一个大的,可怕的注释在类的定义中,强调他们的秩序的重要性。 。
- 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.
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 in 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:
In your concrete example this doesn't matter, so you are safe to do this.
这篇关于在初始化列表中调用函数有什么问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!