If I override operator=
will the copy constructor automatically use the new operator? Similarly, if I define a copy constructor, will operator=
aut
No, they are different operators.
The copy constructor is for creating a new object. It copies a existing object to a newly constructed object.The copy constructor is used to initialize a new instance from an old instance. It is not necessarily called when passing variables by value into functions or as return values out of functions.
The assignment operator is to deal with an already existing object. The assignment operator is used to change an existing instance to have the same values as the rvalue, which means that the instance has to be destroyed and re-initialized if it has internal dynamic memory.
Useful link :
No. Unless you define a copy ctor, a default will be generated (if needed). Unless you define an operator=, a default will be generated (if needed). They do not use each other, and you can change them independently.
No.
And definitely have a look at the rule of three (or rule of five when taking rvalues into account)
No, they are not the same operator.
No. They are different objects.
If your concern is code duplication between copy constructor and assignment operator, consider the following idiom, named copy and swap :
struct MyClass
{
MyClass(const MyClass&); // Implement copy logic here
void swap(MyClass&) throw(); // Implement a lightweight swap here (eg. swap pointers)
MyClass& operator=(MyClass x)
{
x.swap(*this);
return *this;
}
};
This way, the operator=
will use the copy constructor to build a new object, which will get exchanged with *this
and released (with the old this
inside) at function exit.