If we put copy constructor and assign operator as private and provide no implementation, they will be disabled, like this:
class Test
{
private:
Test(const Test&);
Test& operator=(const Test&);
};
but in which case we need to do this? I mean when should we do it like this?
A copy constructor is called when a new object is created from an existing object, as a copy of the existing object. The assignment operator is called when an already initialized object is assigned a new value from another existing object.
The Copy constructor and the assignment operators are used to initializing one object to another object. The main difference between them is that the copy constructor creates a separate memory block for the new object. But the assignment operator does not make new memory space.
Both the copy constructors and assignment operators copies from one object to another then why do we need both? Copyconstructor means it creates a new object and copies the contents from another exist object and assignment operator copies the contents from one existing object to the already existing object.
A cleaner solution: create a class where the default copy constructor and/or default copy assignment operator are deleted. Derive all your classes or the base class of the class hierarchies from this special class. Copy construction and/or copy assignment will now be disabled for all these classes automatically.
When you want the objects of this class to be non-copyable.
There may be many reasons when objects can't be or shouldn't be copied to other objects. A few examples are:
For above examples, compiler provided version of default copy constructor and default assignment operators may lead to unexpected results.
c++11 onwarnds, you can use =delete
syntax to delete the compiler provided default versions.
Another use is to force (restrict) copying of objects only via class utilities virtual Base* clone()
for example.
Related: Rule of three or rule of five
Another common case is when the object is not shallow-copyable and the one who wrote the class doesn't want to implement deep copy for it, so he left those two disabled, with or without comments on the rationale.
For example, when constructor new
s an array and destructor delete
s it, then the object not shallow-copyable. To implement deep copy, copy constructor needs to new an empty array to the same size and then copy each and every element, and copy-assignment has to delete
the old one before doing the same thing.
It's a lot of boilerplate code to write. And it takes time to run, too.
So if this class is private to an implementation and copy-constructor and copy-assignment are neither mandatory nor helpful, why not just disable them?
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