Implementation of the String Class Ultimate Edition

Source: Internet
Author: User

Write-time copy (COW) implementation:

#include <iostream> #include <cassert>using namespace std;class string{public:string ( Char *str= ""): _str (New char[strlen (str) +sizeof (int) +1]) {* (int*) _str=1;_str+=4;strcpy (_STR,STR);} String (CONST&NBSP;STRING&AMP;&NBSP;STR): _str (STR._STR) {+ + (* (int*) (_str-4));} ~string () {if (_str!=null) {if (--(* (int*) (_str-4))) {delete[]  (_str-4);}} String& operator= (CONST&NBSP;STRING&AMP;&NBSP;STR) {if (THIS!=&AMP;STR) {if (--(* (int*) (_str-4))) {delete[ ]  (_str-4);} _str=str._str;++ (* (int*) (_str-4));} Return *this;} Char& operator[] (Int index) {assert (Index>=0 && index<strlen (_STR)); _str[ index]=* (_str+index); return _str[index];} friend ostream& operator<< (OSTREAM&AMP;&NBSP;OS,CONST&NBSP;STRING&AMP;&NBSP;STR);p rivate: Char *_str;};o stream& operator<< (ostream& os,const string& str) {Cout<<str._str <<endl;return os;} Int main () {//STRING&NBSP;S1("Hello"); STRING&NBSP;S2 ("ABCDEFG"); Cout<<s2;cout<<s2[0];getchar ();//string s3=s2;//string s3 (S2); return 0;}


This article is from the "July boreas" blog, please be sure to keep this source http://luminous.blog.51cto.com/10797288/1749228

Implementation of the String Class Ultimate Edition

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.