Implementing the copy constructor in terms of operator=

后端 未结 8 1922
自闭症患者
自闭症患者 2020-12-28 16:19

If the operator= is properly defined, is it OK to use the following as copy constructor?

MyClass::MyClass(MyClass const &_copy)
{
    *this          


        
相关标签:
8条回答
  • 2020-12-28 16:55

    @Alexandre - I am not sure about passing by value in assignment operator. What is the advantage you will get by calling copy constructor there? Is this going to fasten the assignment operator?

    P.S. I don't know how to write comments. Or may be I am not allowed to write comments.

    0 讨论(0)
  • 2020-12-28 17:03

    This implementation implies that the default constructors for all the data members (and base classes) are available and accessible from MyClass, because they will be called first, before making the assignment. Even in this case, having this extra call for the constructors might be expensive (depending on the content of the class).

    I would still stick to separate implementation of the copy constructor through initialization list, even if it means writing more code.

    Another thing: This implementation might have side effects (e.g. if you have dynamically allocated members).

    0 讨论(0)
提交回复
热议问题