Copy Constructors and Assignment Operators

Copy Constructors and Assignment Operators: Just Tell Me the Rules! Part I

I get asked this question sometimes from seasoned programmers who are new to C++. There are plenty of good books written on the subject, but I found no clear and concise set of rules on the Internet for those who don’t want to understand every nuance of the language—and just want the facts.

Hence this article.

The purpose of copy constructors and assignment operators is easy to understand when you realize that they’re always there even if you don’t write them, and that they have a default behavior that you probably already understand. Every struct and class have a default copy constructor and assignment operator method. Look at a simple use of these.

Start with a struct called Rect with a few fields:

struct Rect {
   int top, left, bottom right;
};

Yes, even a struct as simple as this has a copy constructor and assignment operator. Now, look at this code:

1: Rect r1 = { 0, 0, 100, 200 };
2: Rect r2( r1 );
3: Rect r3;
4: r3 = r1;

Line 2 invokes the default copy constructor for r2, copying into it the members from r1. Line 3 does something similar, but invokes the default assignment operator of r3, copying into it the members from r1. The difference between the two is that the copy constructor of the target is invoked when the source object is passed in at the time the target is constructed, such as in line 2. The assignment operator is invoked when the target object already exists, such as on line 4.

Looking at what the default implementation produces, examine what Line 4 ends up doing:

1. r3.top    = r1.top;
2. r3.left   = r1.left;
3. r3.bottom = r1.bottom;
4. r3.right  = r1.right;

So, if the default copy constructor and assignment operators do all this for you, why would anyone implement their own? The problem with the default implementations is that a simple copy of the members may not be appropriate to clone an object. For instance, what if one of the members were a pointer that is allocated by the class? Simply copying the pointer isn’t enough because now you’ll have two objects that have the same pointer value, and both objects will try to free the memory associated with that pointer when they destruct. Look at an example class:

class Contact {
   char* name;
   int age;
public:
   Contact( const char* inName, inAge ) {
   name = new char[strlen( inName ) + 1];
   strcpy( name, inName );
   age = inAge;
   }
   ~Contact() {
      delete[] name;
   }
};

Now, look at some code that uses this class:

Contact c1("Fred", 40 );
Contact c2 = c1;

The problem is, c1 and c2 will have the same pointer value for the “name” field. When c2 goes out of scope, its destructor will get called and delete the memory that was allocated when c1 was constructed (because the name field of both objects have the same pointer value). Then, when c1 destructs, it will attempt to delete the pointer value, and a “double-free” occur. At best, the heap will catch the problem and report an error. At worst, the same pointer value may, by then, be allocated to another object, the delete will free the wrong memory, and this will introduce a difficult-to-find bug in the code.

The way you want to solve this is by adding an explicit copy constructor and an assignment operator to the class, like so:

Contact( const Contact& rhs ) {
   name = new char[strlen( rhs.name ) + 1];
   strcpy( name, rhs.name );
   age = rhs.age;
}

Contact& operator=( const Contact& rhs ) {
   char* tempName = new char[strlen( rhs.name ) + 1];
   delete[] name;
   name = tempName;
   strcpy( name, rhs.name );
   age = rhs.age;
   return *this;
}

Now, the code that uses the class will function properly. Note that the difference between the copy constructor and assignment operator above is that the copy constructor can assume that fields of the object have not been set yet (because the object is just being constructed). However, the assignment operator must handle the case when the fields already have valid values. The assignment operator deletes the contents of the existing string before assigning the new string. You might ask why the tempName local variable is used, and why the code isn’t written as follows instead:

delete[] name;
name = new char[strlen( rhs.name ) + 1];
strcpy( name, rhs.name );
age = rhs.age;

The problem with this code is that if the new operator throws an exception, the object will be left in a bad state because the name field would have already been freed by the previous instruction. By performing all the operations that could fail first and then replacing the fields once there’s no chance of an exception from occurring, the code is exception safe.

Note: The reason the assignment operator returns a reference to the object is so that code such as the following will work:

c1 = c2 = c3;

One might think that the case when an explicit copy constructor and assignment operator methods are necessary is when a class or struct contains pointer fields. This is not the case. In the case above, the explicit methods were needed because the data pointed to by the field is owned by the object. If the pointer is a “back” (or weak) pointer, or a reference to some other object that the class is not responsible for releasing, it may be perfectly valid to have more than one object share the value in a pointer field.

There are times when a class field actually refers to some entity that cannot be copied, or it does not make sense to be copied. For instance, what if the field were a handle to a file that it created? It’s possible that copying the object might require that another file be created that has its own handle. But, it’s also possible that more than one file cannot be created for the given object. In this case, there cannot be a valid copy constructor or assignment operator for the class. As you have seen earlier, simply not implementing them does not mean that they won’t exist, because the compiler supplies the default versions when explicit versions aren’t specified. The solution is to provide copy constructors and assignment operators in the class and mark them as private. As long as no code tries to copy the object, everything will work fine, but as soon as code is introduced that attempts to copy the object, the compiler will indicate an error that the copy constructor or assignment operator cannot be accessed.

To create a private copy constructor and assignment operator, one does not need to supply implementation for the methods. Simply prototyping them in the class definition is enough. Example:

private:
Contact( const Contact& rhs );
Contact& operator=( const Contact& rhs );

Some people wish that C++ did not provide an implicit copy constructor and assignment operator if one isn’t provided. They automatically define a private copy constructor and assignment operator automatically when they define a new class. That way, it will prevent anyone from copying their object unless the explicitly support such an operation. This is generally a good practice.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read