Home > Articles > Programming > C/C++

Move Semantics in C++11, Part 1: A New Way of Thinking About Objects

Not every resource transfer is a copy operation. In many programming tasks, the resource only moves from one object to another, emptying the source object in the process. The semantics and formal properties of these 'move semantics' are a new C++11 paradigm to make code more efficient and simulate real-world situations more accurately, as Danny Kalev explains in this two-part series.
Like this article? We recommend

Like this article? We recommend

Copying objects is an operation that takes a source and a target, yielding two independent objects with identical states. However, many real-life entities don't behave like that—you can move them, but not copy them. For example, when you relocate to a new home, you just end up having a new home after the relocation—not two homes with identical residents and furniture. (Even if you own multiple houses, you can only be in one of them at a time. Moving to a new home doesn't clone you.) In this series, I'll introduce you to move semantics and discuss the formal definitions of copying and moving objects in C++.

The Semantics of Copying

Graphical user interface (GUI) operating systems let you select objects and cut or copy them to a new destination. Cutting moves the original object to a new destination, whereas copying creates a new object, leaving the source object in its original place. This is the classic difference between moving and copying operations. Let's look at other file-oriented operations to pinpoint the differences between move and copy operations.

Suppose you're downloading an MP3 clip from iTunes. At the end of the process you have a local copy of the clip, while the iTunes server still retains its original file. These two files have identical and independent states. Therefore, downloading a file from iTunes is a copy operation. The state of an object is defined as the set of its non-static data members' values. In other words, an object's state is its value. Among other things, an object's state indicates which resources it owns. For example, a string object that allocates memory has a non-null pointer member and a counter that keeps track of the buffer's size. Similarly, an MP3 file's state is the set of values of its data bytes.

For this discussion, it's crucial to understand what it means for two objects to have both identical and independent states:

  • Identical states. Two objects o1 and o2 have identical states if each non-static data member in o1 has the same value as does its corresponding data member in o2.
  • Independent states. Two identical objects have independent states if changing the state of one object doesn't affect the state of the other object. For example, if iTunes deleted or altered its file after you downloaded it, your private copy would remain intact, and vice versa.

Let's apply the state independence principle to two strings:

char s1[]="abc";
char s2[]="abc";

The states of s1 and s2 are identical. Furthermore, modifying the state of s1 doesn't affect the state of s2. Hence, the strings have independent states, as the following listing shows:

s1[0]='d';
cout<<s1<<'\t'<<s2<<endl;

The output of the statement above is as follows:

dbc      abc

In certain cases, you can have two or more objects whose states are identical but not independent. For example, the smart pointer std::shared_ptr shares its resource among all of its instances. Changing the resource through one of the instances affects every other instance automatically. Therefore, what appears to be a copy operation of shared_ptr objects isn't a pure copy operation, because the resulting objects don't have independent states.

Now that we've defined pure copy semantics, let's look at another real-world scenario. Suppose you're visiting a gallery of paintings, and you're so impressed that you decide to purchase one of the paintings for your living room. Is purchasing an original painting a copy operation? No. After your purchase, that object is in the same state as before the purchase, although it has moved from the gallery to your home. Let's try to imagine a scenario in which purchasing a painting would count as copying. Instead of selling you the original painting, suppose the gallery offered to sell you a replica, made on demand from the original painting. In that case, the purchasing operation would indeed be a copy operation, as it would generate a new object with the same content, while leaving the original painting on the gallery wall.

Back to strings. A trivial example of moving strings might look like this:

char *s1 = new char[4] {"abc"};
char *s2=nullptr;
//moving in action
s2=s1;
s1=nullptr;

This move operation transferred the ownership of the memory buffer from s1 to s2. Consequently, you have only one object with the original state, except that the owning object is now s2 rather than s1. As with copying, moving involves two objects, but the end result is that only the target object has the desired state. After the move operation, the source object's state is unspecified. In general, you shouldn't assume that a moved-from object has retained its pre-move state.

Time to Move

The topic of move semantics is interesting, but why would you want your programming language to support it? Because copying objects is an expensive operation. It requires a lot of memory and a large number of CPU cycles, especially when large objects such images, video clips, or census data files are involved. You may be surprised to learn that C++ copies objects silently in many cases. For example, take a function that returns an object by value:

string concat (const string & s1, const string & s2)
{
string res=s1;
return res+s2;
}
string one, two;
string s=concat (one, two);

Consider this question: How many copies of the local object res are created and destroyed when the statement string s=concat (one, two); is executed? Too many, that's for sure! When concat() returns, it copy-constructs a temporary string object on the caller's stack, and the local string res is destroyed. Next, the implementation copy-constructs s using the temporary string as its argument. Finally, the temporary is destroyed. You need two copy constructions and two destructor calls to copy the content of res to s! This overhead is certainly unnecessary, because its sole purpose is to move the content of res to s.

The creators of C++ became aware of this problem long ago. They even designed a specific optimization technique to eliminate spurious copies (and destructor calls), known as named return value (NRV) or return value optimization (RVO). With RVO, the compiler rewrites the code of concat() so that, instead of returning an object by value, the function conceptually takes a third reference argument to the target object.

The revised concat() writes the result to the target object directly, as shown here:

//pseudo code
void __concat( string & __result, const string &s1, const string & s2)
{
__result=s1;
__result+=s2;
return;
}

Similarly, the compiler rewrites the former function call as if the programmer had written the statement this way:

//pseudo code
string one, two, __result;
__concat(__result, one, two); // no objects are copied or destroyed in this version

Return value optimization is neat, but it still has two flaws:

  • It's optional. Indeed, some compilers don't implement RVO for various reasons.
  • RVO doesn't eliminate the root problem; that is, the creation of spurious copies when all you really need is to move a value.

In Quest of Perfect Forwarding

The challenge is to design a perfect forwarding mechanism that lets you pass values directly to the target, without introducing temporary copies along the way. When thinking of such a mechanism, the notion of reference variables springs to mind. References are an efficient vehicle for accessing objects without copying them. However, the traditional references of C++ can only bind to lvalues; that is, named objects that can appear on the left side of an assignment expression. Temporaries, literals, and other objects that don't support pure copying (such as auto_ptr) can't bind safely to reference variables.

Enter Rvalue References

About a decade ago, members of the standards committee started to experiment with a new type of reference variables known as rvalue references. Unlike traditional reference variables (now called lvalue references), rvalue references can safely bind to rvalues. Syntactically, an rvalue reference looks like this:

T&& rref;

Two new canonical member functions were also added to C++11:

  • A move constructor is the move counterpart of a copy constructor. Instead of copying a source object into a target, a move constructor pilfers the resources of the source, moving them to the target. Consequently, after a move construction the source object is left in an unspecified state, and the target object becomes the exclusive owner of those resources. A move constructor has this signature:
  • C::C(C&& );
  • A move assignment operator is the move counterpart of a copy assignment operator. It pilfers the resources of the source object, transferring them to *this. A move assignment operator has this signature:
  • C& C::operator=(C&&);

The early specifications of move operations assumed that after a move operation the source object was left in an unusable state. The only thing you could do with it was to call its destructor. This draconian policy was changed recently; in C++11, it's agreed that a moved-from object is left in an "empty," albeit valid state, similar to that of a default constructed object.

Move Constructors in Action

Technically, you can write a move constructor without using rvalue references. In fact, for a long time several Standard Library containers have been doing just that. Let's see how a move constructor of a simplified string class would work. Assume that a string class has two data members: a pointer to the memory buffer, and a size counter. Moving merely assigns these two data members to the corresponding members of the target, and it sets the source's data members to zeroes:

class string
{
private:
char * buf;
int length;
public:
string(string& source) //naive move constructor without rvalue references
{
  this->buf=source.buf;
  source.buf=nullptr;
  this->length=source.length;
  source.length=0;
}
};

By contrast, a copy constructor would be much more expensive in terms of performance, since it must allocate dynamic memory and copy the source's characters one by one:

string(const string& source) //copy ctor with proper copy semantics
{
  this->buf= new char [source.length];
  strncpy(this->buf, source.buf, source.length);
  this->length=source.length;
};

This leaves us with a new dilemma—should string classes use copy semantics or move semantics? Clearly, using move semantics is more efficient. However, in certain cases you really want two independent copies of a string. Part 2 of this series will explain how to choose between copy and move semantics; you'll learn how to use C++11 rvalue references to define move canonical member functions, namely the move constructor and the move assignment operator; and finally, you'll overload function sets that take rvalue references and lvalue references.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020