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?
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