2006-01-20

C++ | Be careful when writing assignment operators

If you are writing an assignment operator for a class, be very careful and ensure each of the following :

- that you have copied all the attributes
- that you have allocated new memory for each non-stack attribute (i.e. pointer variable) before copying it.

The second one is the one where most mistakes are made. One tends to copy the address pointed to by the source variable into the destination variable, which is perfectly legal but rarely intended. And then somewhere during runtime, the address in the source copy is freed and later, the address in the destination copy is accessed. And then guess what happens !

0 Comments:

Post a Comment

<< Home