If the operator=
is properly defined, is it OK to use the following as copy constructor?
MyClass::MyClass(MyClass const &_copy) { *this = _copy; }
The implicitly declared copy assignment operator of a class A will have the form A& A::operator=(const A&) if the following statements are true: A direct or virtual base B of class A has a copy assignment operator whose parameter is of type const B& , const volatile B& , or B .
Copy Constructor in C++ClassName (const ClassName &old_obj); Copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. Copy constructor takes a reference to an object of the same class as an argument.
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to − Initialize one object from another of the same type. Copy an object to pass it as an argument to a function.
If all members of MyClass
have a default constructor, yes.
Note that usually it is the other way around:
class MyClass { public: MyClass(MyClass const&); // Implemented void swap(MyClass&) throw(); // Implemented MyClass& operator=(MyClass rhs) { rhs.swap(*this); return *this; } };
We pass by value in operator=
so that the copy constructor gets called. Note that everything is exception safe, since swap
is 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 as
MyClass& MyClass::operator=(MyClass const& rhs) { MyClass tmp(rhs); tmp.swap(*this); return *this; }
C++ 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 rhs
anyway, so passing by value is fine.
Thus, the operator=
(first version, call by value) reads:
rhs
(via the copy constructor, automatically called)*this
*this
and let rhs
(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 rhs
is temporary, no copy is made. We are left with:
this
and rhs
contentsrhs
So passing by value is in this case more efficient than passing by reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With