Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 9 Feb 2008
Rate this:
Please Sign up or sign in to vote.
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.

Introduction

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" occurs. 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 );

This will disable the default copying semantics supplied by C++ for all classes.

Some people wish that C++ did not provide an implicit copy constructor and assignment operator if one isn't provided by the programmer. To simulate this desire, these programmers always define a private copy constructor and assignment operator when they define a new class, and thus the above three lines are a common pattern. When used, this pattern will prevent anyone from copying their object unless they explicitly support such an operation.

This is good practice: Unless you explicitly need to support deep copying of the instances, disable copying using the above technique.

(Another advantage of disabling copying is that auto_ptr can be used to manage a data-members lifetime, but that's probably another article.)

Conclusion

Many C++ programmers simply aren't interested in the details of copy-constructor and assignment operator semantics. This article should be useful to them. It provides just enough information, a pattern than they can use, to ensure that they're doing the right thing.

If anyone finds this article still too complex, please let me know how I can simplify it.

History

  • 9th February, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Kenneth Kasajian

United States United States
My interests mostly revolve around making machines do work for people. I'm a computer programmer, software architect, development manager, program manager and a computer programmer. I said programmer twice because I believe you need to be able to do the work yourself if you're going to direct others. I started my career creating software for abstract art, followed by work in embedded systems and HMI. In the 90s I created a successful product called Visual DLL and helped develop the Sales Force Automation product, Arsenal. I've often been involved in online communities, creating games, utilities, and collaboration software. I'm passionate about agile requirements management, acceptance testing through executable specification, and anything that will make developers more productive. My current role is Principal Scientist where I get to work on different technologies with an awesome team, to solve real-world practical problems. I'm Armenian, so talking is in my nature -- if you see me online or offline, say hi and we'll geek out about the latest tools and libraries. If you learned something cool recently (and you should if you're a lifelong learner), then I'd like to hear about it.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionForgot to check for self-assignment PinmemberSergey Chepurin24-Oct-11 2:29 
AnswerRe: Forgot to check for self-assignment PinmemberKenneth Kasajian24-Oct-11 17:23 
GeneralRe: Forgot to check for self-assignment PinmemberSergey Chepurin25-Oct-11 0:48 
GeneralMy vote of 5 Pinmemberryan20fun16-Aug-11 7:31 
GeneralMost to the point article differentiating between copyCTOR and = overloading. Pinmembertoajeet24-Jun-10 9:24 
GeneralRe: Most to the point article differentiating between copyCTOR and = overloading. PinmemberKenneth Kasajian2-Jul-10 9:22 
Questionwhat about c1 = c1 Pinmemberx-b11-Feb-08 2:15 
AnswerRe: what about c1 = c1 PinmemberBrian Ensink11-Feb-08 3:56 
GeneralRe: what about c1 = c1 PinmemberKenneth Kasajian11-Feb-08 5:47 
GeneralRe: what about c1 = c1 Pinmemberx-b13-Feb-08 1:07 
GeneralRe: what about c1 = c1 PinmemberKenneth Kasajian25-Apr-08 9:23 
AnswerRe: what about c1 = c1 PinmemberKenneth Kasajian11-Feb-08 5:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 9 Feb 2008
Article Copyright 2008 by Kenneth Kasajian
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid