Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c++ - 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 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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is there a problem to initialize numRow, numCol in the initialization list [...]?

In general, there's two problems with doing so:

  1. 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.
  2. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...