| 277 | === Copy and Assigment constructors are potentially dangerous === #code-good-bad-copy-assignment |
| 278 | |
| 279 | Copy constructors such as |
| 280 | {{{ |
| 281 | class A { |
| 282 | public: |
| 283 | A(); |
| 284 | A(class A&); |
| 285 | ~A(); |
| 286 | |
| 287 | A& operator = (const class A&); |
| 288 | } |
| 289 | }}} |
| 290 | are dangerous to implement by hand and not leave it to the compiler, which generally does a good job. This is especially the case for derived classes with self-implemented copy constructors, where the copying of base class elements is often forgotten. Or when classes are extended by new member attributes and these are not included in the copy constructor as well. |
| 291 | |
| 292 | See to it that unnecessary self-implemented copy constructors are removed and if ... implement a Init() function that both copy constructors use. |
| 293 | |
| 294 | === Check for self-assignment === #code-good-bad-self-assignment |
| 295 | |
| 296 | If you have to implement a copy/assignment operator, always check for self-assignment! |
| 297 | {{{ |
| 298 | SomeClass& SomeClass&::operator=(const SomeClass &instance) |
| 299 | { |
| 300 | if (*this != instance) { |
| 301 | ... |
| 302 | } |
| 303 | } |
| 304 | }}} |