Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

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

share|improve this answer
add comment

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;

share|improve this answer
    
+1 - this is a complete answer to the question, thanks. –  Jarrod Roberson Nov 11 '12 at 4:15
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.