Possible Duplicate:
Why copy constructor and assignment operator are disallowed?
I'm learning C++ from a solid C background, and in the eagerness to avoid the errors of previous C++ that I gleaned from reddit and hacker news, I've been using the Google C++ style guide and LLVM's source code as references for my own code. One thing that sticks out is both the projects' use of the following code. The following is taken from LLVM's include/Support/MemoryBuffer.h:
MemoryBuffer(const MemoryBuffer &); // DO NOT IMPLEMENT
MemoryBuffer &operator=(const MemoryBuffer &); // DO NOT IMPLEMENT
Google echoes this usage. Clearly, it's a good thing to disable these "copy constructors".
So my question is: why are these things so scary, and (if they are not guarded against) what does their use look like and what effect does it cause in code?
When an object has to manage its own resources, such as memory or a system handle, then the default copy constructor and assignment operator are no longer appropriate. That means you have to override them.
However, sometimes it doesn't make any sense to copy such an object. Or, said differently, some objects are not meant to be copied. Sometimes it's not even possible to write such a constructor or assignment operator. In that case, it's best to disable copy and assignment to make sure they're not copied by accident.
The standard's iostream
are a good example.
All in all, it's a, say, special case. Definitely not something you would encounter often.
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