C + + string copy of traced dig bottom! Look at the layers that you understand.

Source: Internet
Author: User

Believe that people who have written C + + must have used:

String str2 ("11");

string str1 = str2;


Now let me dig deep into the string str1 = str2, what it contains.

First Floor:

Copied the contents of str2 "11" to str1.

Second floor:

The STR1 object is defined first, and the Str2 object is assigned to STR1

Third floor:

Why the string type can be assigned, the original string implements the assignment operator overload.

  1. string & string::operate= (const  string &other)   
  2. {  
  3.     if   ( this  == &other)   
  4.         return  * this
  5.     delete  m_data;  
  6.     m_data = new   char [ Strlen (Other.data) +1];  
  7.     strcpy (m_data, other.data);   
  8.      return  * this //  returns a reference to  *this without copying the process   
  9. }
Fourth floor:

Understood to string str1 = str2; The pseudo-code can be written as:

String str1;

str1.= (STR2)

The process of STR1=STR2 is analyzed as follows:

1. Create temporary variable tmp for string&

2. Calling the assignment operator overload function

3, the STR2, str1 in turn to press the stack, the execution function

4, the return value initializes the TMP

5. Destroy TMP

Fifth Floor:

I don't understand:

    1. String & string::operate= (const string &other)
This overloaded function does not need to return a value at all, why return it!

Please help the god to explain!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C + + string copy of traced dig bottom! Look at the layers that you understand.

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.