Looking for non-conceptual/non-contrived reasons of when one would need to use an object with both a private
copy constructor and a private
assignment operator?
As in what problem does this technique/practice solve, that some other technique couldn’t solve?
You can look at the standard (which has streams).
The stream
objects are non copyable because they hold a non shareable buffer.
If you were to allow copying you would need to define semantics that would allow the transfer of the buffer and still make the source of the transfer usable (what does it mean to use a stream after you have transferred its buffer). Instead they decided it was non copyable.
The stream
are non-assignable for the same reason. Assignment is just the other side of the same coin (assignment is just copying (with over-writting))
0
I wrote a Rand
class one time that handles the generation of random numbers. If I passed the a Rand
instance into a function by value, then the original Rand
object would not update its seed state when the copied value generated numbers. Of course, I could have made the seed state allocated somewhere not in the object itself (such as on the heap). Instead I wanted to pass Rand
objects by reference. To avoid accidentally passing them by value, I disabled its copy constructor and assignment operator (by making them private).
Now I also wanted the user to be able to actually copy a Rand
object. But this requires a little more work since the copy constructor and assignment operators were private. My solution was to create a member function RandForwarder Rand::clone()
, where RandForwarder
was a friend class of Rand
so it could access those private members. I also gave Rand
a public constructor that took a RandForwarder
and an assignment operator of RandForwarder
so users could do this: Rand r2 = r1.clone();
whille disallowing Rand r2 = r1;
0