Implementation of the basic functions of the String class in C + + (1)

Source: Internet
Author: User

1. Traditional method of implementing string class

Advantages: Easy to understand the program

Disadvantages:

1) in the implementation of its copy construction and assignment of the operation of multiple calls to new dynamic space, it is also necessary to delete more than once to free space. It is also prone to memory leaks if handled improperly.

2) The consistency of the program is relatively poor

#include <iostream> #include <string>using namespace Std;class string {public://constructor string (char *str = ""): _ STR (new char [strlen (str) +1]) {if (_str! = NULL) {strcpy (_str, str);}} Copy construction String (const string& str): _str (New Char[strlen (STR._STR) + 1]) {if (_str! = NULL) {strcpy (_str, STR._STR);}} Assignment string& operator = (const string& str) {if (this = &STR)//self-assignment problem {delete[]_str;//released before space _str = new Char[s Trlen (STR._STR) + 1];//opens new space strcpy (_STR, STR._STR);//Copy}return *this;} destructor ~string () {delete [] _str;} Private:char * _STR;};

2, modern implementation of the method of string class realism

Copy Construction Implementation ideas:

A) Create a temporary object and construct it through Cconst string._str.

b) The _str and this._str of the temporary object are exchanged and the object's content is exchanged to complete the copy construction after the construction is completed

Assignment Implementation ideas:

The object is constructed by passing the value of the parameter, and the object's contents are exchanged

Advantages:

1) Program consistency is better

2) Only in the constructor, there is a space-opening new, only in the destructor of the delete structure is clear, not easy to cause memory leaks

Class String {public://constructor string (char *str = ""): _str (New char [strlen (str) +1]) {if (_str! = NULL) {strcpy (_str, str);}} Copy construction String (const string& str): _str (NULL)//prevents it from pointing to an illegal space {String tmp (STR._STR); Swap (_str, tmp._str);} Assignment string& operator = (String str) {swap (_str, str._str); return *this;} destructor ~string () {delete [] _str;} Private:char * _STR;};


3, realistic function to improve the efficiency of string class

In the implementation of the two types of string, there is a problem of efficiency. Sometimes strings are longer, and objects are not necessarily changed after they are created. However, both of these methods need to be constructed at any time, and their efficiency is low and will result in a waste of memory.

We can use the counter to record the number of objects by having all objects pointing to the same string content point to the same space, and avoid the failure of the destructor.

So you can store the counter by opening up more than 4 bytes of space at the time of opening the object. If you change the time to open up space.

#define  _CRT_SECURE_NO_WARNINGS#include<iostream> #include  <string>using namespace  std;class string {public://Constructor String (char *str= ""): _pstr (Findstartref (new char[ strlen (str) +1+sizeof (int)]) {*count (_PSTR)  = 1;//counter strcpy (_PSTR,&NBSP;STR);//Copy string}//copy constructor// If you do not change the contents of the object, point the character pointer of multiple objects to the same space String (const string& s) {_pstr = s._pstr; (*count (_PSTR)) + + ;//Counter plus 1}//assignment statement//If you do not change the contents of the object, let the character pointer of multiple objects point to the same space string& operator = (const string& s) { if  (This != &s)//Avoid self-assignment {if  (--* (Count (_PSTR))  == 0) {Delete[]finddel (_PSTR);} Only one portion of the space used by an object is released else{_pstr = s._pstr; (*count (_PSTR)) + +;}} Return *this;} destructor ~string () {if  (--* (Count (_PSTR))  == 0) {Delete[]finddel (_PSTR);}} public://find the first address of the storage string when opening space Char * findstartref (CHAR*&NBSP;STR) {return  (str + 4);} Find the first address when freeing space Char * finddel (Char* del) {return  (del -&NBSP;4);} Locate the counter's first address Int *count (CHAR*&NBSP;STR) {return  (int *) (str - 4);} public://Modifying the content function of a realistic object char & operator[] (int index) {if  (--* (Count (_PSTR))  != 0) {Char * tmp = _pstr;_pstr = findstartref (New char[strlen (_PSTR)  +  1 + sizeof (int)]); *count (_PSTR)  = 1;//counter 1strcpy (_pstr, tmp);} If the object and other objects share a space else{//a separate space can be arbitrarily changed}return _pstr[index];} private:char * _pstr;};


Implementation of the basic functions of the String class in C + + (1)

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.