C++11 rvalue Reference (iii): Writing the String class with c++11 and the = operator for "Exception safe"

Source: Internet
Author: User
Tags types of functions

The preceding two sections describe the Rvalue reference and its effect. The use of rvalue references is described below through the writing of a string class.

With respect to c++98, the movement constructor and the move assignment operator are the main functions .

Give a brief statement first:

classstring{ Public: String (); String (Const Char*s);//Conversion SemanticsString (ConstString &s); String (String&&s); ~String (); String&operator=(ConstString &s); String&operator= (String &&R); Friend Ostream&operator<< (Ostream &os,ConstString &s) {returnOS <<S.data_; }Private:    Char*Data_;};

Each function is implemented in turn below.

The first one is the default constructor:

string::string ():d ata_ (newchar[1]) {    0;     " default " << Endl;}

Then there is the char* version of the constructor:

String::string (constChar *s):d Ata_ (newchar1]) {    :: strcpy (Data_, s);     " char * " << Endl;}

The point is that we provide the move constructor:

String::string (String &&s):d Ata_ (s.data_) {    "move construct" << Endl;     // prevent release of data}

The most important point here is to set the data of S to NULL, because S is a right value and is immediately to be destructor. This will successfully achieve the theft of S content .

Destructors:

string::~String () {    delete[] data_;}

Here we provide an assignment operator, which is noted here:

One is to handle the self-assignment, and the other is to return the reference itself.

String &string::operator=(ConstString &s) {    if( This! = &s) {delete[] data_; Data_=New Char[Strlen (S.data_) +1];    :: strcpy (Data_, S.data_); }    return* This;} String&string::operator= (String &&s) {    if( This! = &s) {cout<<"Move Assignment"<<Endl;        Delete[] Data_; Data_=S.data_; S.data_=NULL; }    return* This;}

After the move constructor, you still have to set the data of S to null.

The above two functions appear to be correct, but do not handle the case of exception, if new is an exception, but at this time the original data has been deleted, resulting in an error.

How to solve?

We provide a swap function:

void String::swap (String &s) {    std::swap (Data_, S.data_);}

A good treatment scheme is:

String &string::operator= (const string &s) {    string temp (s);    Swap (temp);     return *This &string::operator= (string &&s) {    string Temp (s);    Swap (temp);     return *this;}

This way, even if an exception occurs when you generate temp, it has no effect on itself.

Note that the self-assignment is not handled here because the self-assignment is actually relatively small, and the first line of the previous code is delete, and the self-assignment must be handled.

The above two assignment operators can be directly combined as one:

String &string::operator=(String s) {    swap (s);     return *this;}

In fact, as we mentioned earlier, in addition to constructors, X &x and X && types of functions can be combined into X x, using the value of the pass.

In this way, our last implementation guarantees exceptional security.

Test code:

intMainintargcChar Const*argv[]) {String S ("Foo");    String S2 (s); //string S3 (Std::move (String ("Bar")));String S3 (String ("Bar"));//compiler optimizations for direct use of char*cout << S3 <<Endl; S3=s; S3= String ("Hello"); cout<< S3 <<Endl; S3=std::move (S2); cout<< S3 <<Endl; return 0;}

Attention:

String S3 (String ("bar"));

will be optimized by the compiler to

String S3 ("Bar")

Can be used explicitly:

String S3 (Std::move (String ("bar")));

Complete.

C++11 rvalue Reference (iii): Writing the String class with c++11 and the = operator for "Exception safe"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.