If the operator= is properly defined, is it OK to use the following as copy constructor?
MyClass::MyClass(MyClass const &_copy)
{
*this = _copy;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If all members of
MyClasshave a default constructor, yes.Note that usually it is the other way around:
We pass by value in
operator=so that the copy constructor gets called. Note that everything is exception safe, sinceswapis guaranteed not to throw (you have to ensure this in your implementation).EDIT, as requested, about the call-by-value stuff: The
operator=could be written asC++ students are usually told to pass class instances by reference because the copy constructor gets called if they are passed by value. In our case, we have to copy
rhsanyway, so passing by value is fine.Thus, the
operator=(first version, call by value) reads:rhs(via the copy constructor, automatically called)*this*thisand letrhs(which contains the old value) be destroyed at method exit.Now, we have an extra bonus with this call-by-value. If the object being passed to
operator=(or any function which gets its arguments by value) is a temporary object, the compiler can (and usually does) make no copy at all. This is called copy elision.Therefore, if
rhsis temporary, no copy is made. We are left with:thisandrhscontentsrhsSo passing by value is in this case more efficient than passing by reference.