C + + String deep copy (traditional notation + modern notation)

Source: Internet
Author: User

General wording   #include  <iostream>using namespace std;class string{of the c++string  class public: //Constructor  string (char*str =  "")           &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;:_STR (New char[strlen (str)  + 1])  {   strcpy (_STR,&NBSP;STR);  } //copy Construction  string (const string &s)  {  _str  = new char[strlen (S._STR)  + 1];  strcpy (_STR,&NBSP;S._STR);  } // Operator= Heavy-duty  string&operator= (Const string &s)  {  if  (this !=  &s)   {   /*delete[]_str;   _str = new char[ Strlen (S._STR)  + 1];   strcpy (_STR,&NBSP;S._STR); */   char*tmp =  new char[strlen (S._STR)  + 1];   strcpy (TMP,&NBSP;S._STR);    delete[]_str;   _str = tmp;     }  return *this; } // destructor  ~string ()                            {  if  (_STR)   {    delete[]_str;  } } char *cstr ()  {  return _str;  }char& operator[] (Size_t index) { return _str[index];} private: char*_str;};/ The modern notation of/c++string class #include <iostream>using namespace std;class string{public:  String (char*str= "")   :_str (New char[strlen (str) +1])  {  strcpy (_STR,&NBSP;STR);  } string (const string&s)   :_str (NULL)  {  string tmp (S._STR);   swap (_STR,&NBSP;TMP._STR);  } string&operator= (const string &s)  {   if (This ! = &s)   {   string tmp (S._STR);    swap (_str, tmp._ STR);   }  return *this; } // operator=  optimization  String& Operator= (string s)  {  swap (_STR,&NBSP;S._STR);  return *this; }  ~string ()  {  if  (_STR)   {   delete[]_str;  } }  char *cstr ()  {    return _str; }char& operator[] (size_t  index) { return _str[index];} private: char*_str;};

This article is from the "printf Return Values" blog, so be sure to keep this source http://10741125.blog.51cto.com/10731125/1754454

C + + String deep copy (traditional notation + modern notation)

Related Article

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.