Home>Articles>Programming>C/C++

Move Semantics in C++11, Part 2: Design and Implementation of Special Move Functions

Move semantics in C++11 can improve your code's performance dramatically. Danny Kalev concludes this series with a close look at the design and implementation of move-enabled code. Find out what the state of a moved-from object should be, and learn the guidelines for writing move constructors and move assignment operators.
Like this article? We recommend

Part 1 of this series presented the semantics of C++11 move operations and their effects on the source and target. This article concludes this series by focusing on the formal properties of moving, providing guidelines for designing move functions, and illustrating the standard C++ move features.

The State of Moved-from Variables

According to the C++11 standard, the state of a moved-from object is unspecified, albeit valid. This loose definition gives implementers enough leeway to do all sorts of things when moving. For example, a moved-from object might be left in an "empty" state, similar to a default constructed object. Another option is to leave the moved-from object in its pre-move state. The policy you should employ depends on the properties of the type and its usage. Let's look at moved-from objects that retain their original value.

When moving from fundamental types such asintandfloat, the source variable may retain its original value:

int m=7, n=0; n=m; //"move" m to n.

Seemingly, the programmer should setmto zero because a moved-from object is usually left in a default-initialized state. However, we can think of good reasons whym应该留下完整:

  • In many cases, a moved-from object is discarded immediately after the move operation. If it has no destructor, it's more efficient to leave the moved-from object intact.
  • The C++11 requirement that a moved-from object has an unspecified state is satisfied even ifmremains intact.

You therefore need to zeromonly if you have a reason to do so. What might be a good reason for zeroing a variable after a move operation? Suppose you have two pointersp1andp2and you want to movep1top2. Leavingp1intact could be disastrous because destructors and cleanup code assume that a non-null pointer value indicates resource ownership. This approach could lead to the infamous aliasing problem where two pointers hold the same address. To avoid aliasing, always set a moved-from pointer tonullptr:

int *p1= new int(5); int *p2=nullptr; //move p1 to p2 p2=p1; p1=nullptr; delete p2; //ok delete p1; //also ok; deleting a null pointer is harmless

Moving Class Objects

If a variable represents resource ownership, you should set it to its default value explicitly, even if it's not a pointer. Consider:

class String { size_t len; char * buf; bool empty; //.. };

Question: Which of the three data members in this example (len,buf, andempty) should be set to zero in a moved-fromString? Answer: All three of them. Obviously,bufshould be set tonullptrto avoid aliasing. Certain applications may assume that iflenisn't zero or ifemptyisn'ttruethen theStringobject still owns resources. Therefore,everyvalue that indicates resource ownership should be set to zero—not just pointers. If you're not sure about the value of a data member, use the default constructor as your guide: The state of a moved-from object should be that of a default-initialized object.

Special Member Functions

The move constructors and move assignment operator are collectively known asmove special member functions. They present a dilemma: Which of the two, if any, should your class define?

Under certain conditions, C++隐式声明the special member functions in a class that doesn't declare them explicitly. In C++11, this rule also applies to the two move special member functions. Thus, if the definition of classCdoesn't explicitly declare a move assignment operator, one will be implicitly declared asdefaultedonly ifallof the following conditions are met:

  • Cdoesn't have a user-declared copy constructor.
  • Cdoesn't have a user-declared move constructor.
  • Cdoesn't have a user-declared copy assignment operator.
  • Cdoesn't have a user-declared destructor.
  • The move assignment operator would not be implicitly defined asdeleted.

Consider the following class:

struct S { int n; S& operator=(const S&) = default; };

C++ will not implicitly declare a move assignment or a move constructor for classCin this case becauseChas a user-declared assignment operator. By contrast, classTin the following example will have both an implicitly declared move assignment operator and an implicitly declared move constructor:

class T { int n; public: T(); };

What does an implicitly defined move special member function do? This issue was under debate for a long time. However, the final resolution says that an implicitly defined move assignment operator performs a member-wise move, typically by callingstd::move()(a new standard function that I'll discuss shortly).

C++11 Move Facilities

C++11 introduced several new facilities for moving. One of them is thestatic_castexpression:

static_cast(t);

Thestatic_castexpression converts thelvaluetto anrvalue referenceof typeT&&. This way, you can select which overloaded version of a function will be selected:f(T&&)orf(T&).

A class can define both move special member functions and copy special member functions. The designer of classStringtherefore may choose to define all six special member functions without risking ambiguity. The move special member function will be invoked when its argument is, or is convertible toString&&. Otherwise, the copy special member functions will be invoked.

Let's look at a concrete example of a legacy class that defines all four of the C++03 special member functions and that needs a C++11 facelift:

class String { public: // copy constructor String(const String& other) :len(other.len), buf(new char[other.len]) { std::cout << "In String's copy constructor. length = " << len << "." << std::endl; std::copy(other.buf, other.buf+len, buf); } // copy assignment operator String& operator=(const String& other) { std::cout << "In String's copy assignment operator. length = " <0) buf= new char [len]; else buf=nullptr; } ~String() { std::cout << "In String's destructor. length was" << len << "." << std::endl; delete[] buf; //even if buff is 0, this delete[] is safe len=0; } private: size_t len; char* buf; };

When implementing move special member functions, adhere to the following guideline:

  1. The target object must release its resources (if any) before acquiring new resources.
  2. Acquire the resources.
  3. Set the source's data members to their default values.

Here's howString's move constructor looks like (thecoutstatements will enable you to see which special member function is called):

String::String(String&& other) //the canonical signature of a move constructor //first, set the target members to their default values : buf(nullptr) , len(0) { std::cout << "In String's move constructor. length = " <
       

In a similar vein, the move assignment operator looks like this:

字符串的字符串::操作符=(字符串& &其他)/ / canonical signature of a move assignment operator { std::cout << "In String's move assignment operator. length = " <
       

Overloading with rvalue References

The C++11 overloading rules recognize rvalue references. In addition, many Standard Library components now define overloaded sets of functions that take eitherT&orT&&as their parameters. If the argument is an rvalue, theT&&overloaded function will be selected. Otherwise, theconst T&overloaded function will be selected:

#include  using namespace std; int main() { vector vs; vs.push_back(String(25)); //the string's size lets you track specific objects v.push_back(String(50)); // insert a new element into the second position v.insert(v.begin() + 1, String(60)); }

When executing the program above, a C++11-compliant implementation will invoke only the move special member functions ofStringbecause in all three function calls the argument is an rvalue. More specifically it's anxvalue; that is, a temporary. (Thexis a hint that the object is about to expire shortly after its creation.) xvalues bind to rvalue references. However, if you use an lvalue argument,push_back(const T&)will be selected instead:

vector vs; String s(15); vs.push_back(s); //uses String's copy constructor

Even with lvalue arguments, you can force the implementation to select the move special member functions. For this purpose, either cast the lvalue toT&&usingstatic_cast, or use the standard functionstd::move()to do the same thing with fewer keystrokes:

vector vs; String s1(15), s2(20); vs.push_back(static_cast(s1)); //uses String's move constructor vs.push_back(std::move(s2)); //uses String's move constructor

Conclusion

The move special member functions are significantly faster than their copy counterparts. Therefore, object copying can be replaced by moving in the following cases:

  • You're populating a container with temporaries.
  • A function is returning an object by value.
  • You're passing an argument by value.

语义是一个的性能优势of the prominent bonuses of using C++11. If you're designing new classes, consider adding the move special member functions to them. Some of your legacy classes probably could also benefit from a C++11 facelift that includes those special member functions.

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.

本隐私通知概述我们的有限公司mmitment 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, simplyemailinformation@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 ourContact 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 theAccount page. If a user no longer desires our service and desires to delete his or her account, please contact us atcustomer-service@informit.comand 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.e-skidka.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 toNevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read ourSupplemental privacy statement for California residentsin conjunction with this Privacy Notice. TheSupplemental privacy statement for California residentsexplains 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


Pleasecontact usabout 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