Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(The avoidance of) Copy mechanics in C++ [duplicate]

Tags:

c++

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?

like image 538
duane Avatar asked Oct 31 '11 20:10

duane


1 Answers

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.

like image 172
Etienne de Martel Avatar answered Oct 06 '22 11:10

Etienne de Martel