C + + class with pointer member (s)

Source: Internet
Author: User

    • As the title shows: This review class with a pointer type member

Consider the following actions to design a class

 1  { 2   String S1 ();  3  String S2 ( " hello   "  4   String S3 (S1);  5  cout << S3 << Endl;  6  S3 = S2;  7  cout << S3 << Endl;  8 } 

The second and third rows in the function body are constructors, one with parameters and one without parameters. Row four creates an object with the initial value of S1, which is a copy of the action, requires a copy constructor, and then the next line is output, which requires an operator overload. Line six is an assignment, a copy of the action, so that lines fourth and sixth are copy actions, so the two operations require a different function, and the sixth line requires a copy assignment operation. If, we do not write, the compiler will give the default two operation functions, like the example of the last plural, the use of the compiler, and this string example, using the default will appear bad, imagine, we now have a pointer object, point to an address, and now create a new object, If just copy, copy the pointer over, point to the same place, this is not a real copy, so as long as the class contains a member with pointers, do not use the default copy constructor and copy assignment operation. The general design of the So,string class is as follows:

1 classString {2  Public:3String (Const Char* CStr =0);//construct func4     //if only the CALSS with pointer Pamater (s), we need design, functions as follow5String (Conststring& str);//copy construct func,the parameter type is Itsown type6string&operator=(Conststring& str);//copy assign,the parameter is Itsown type7 8~String ();9     Char* GET_C_STR ()Const{returnm_data;}Ten Private: One     Char* M_DATA;//because the string is variable in length, it is set to a dynamic array-pointer A};

Here are some of the above functions to be designed

    • Constructors and destructors
1 inline2String::string (Const Char* CStr =0)3 {4     if(CStr) {//with initial value5M_data =New Char[Strlen (CStr +1)];6 strcpy (m_data, CStr);7     }8     Else {9M_data =New Char[1];Ten*m_data =' /'; One     } A } -  - inline thestring::~String () - { -     Delete[] m_data;// Clean Up -}

Use the above function

{String S1 ();    String S2 ("hello");    StringNew string ("hello");     Delete p; // before leaving, release }

The first two, will be released automatically when you leave, but also call the destructor, so the above function within the scope of the departure will call three destructors

The previous plural classes do not need to be cleaned up, because they are going to die, so it is not necessary, but, here is the dynamic allocation of memory, if not released, is a memory leak. So, note: If class contains pointer members, it is most likely to allocate memory dynamically, then the object dies before the destructor call, freeing the dynamically allocated memory

    • Copy constructors and copy assignment operations

Class with pointer member (s), be sure to do this, see the picture below (from Houtie Teacher's courseware)

First, look at the first case (the second picture), using the default copy construct function, the object's data is a pointer, as for the contents of the pointer (' Hello ') is not part of this pointer, and when doing a copy action, B is also a pointer, so two pointers point to the same piece of content. Although A and B also have the same content, but the content in B, there is no pointer to it, and here ' hello ' in the memory block, there are two pointers to it at the same time, in the future, if the change of a, a, the content of the point will also be changed. is a shallow copy, which corresponds to a deep copy, which is what we write our own function to do. Let's see what the deep copy is.

// Copy construct fuction inlinestring::string (const string& str) {    newchar1 ];    strcpy (M_data, str.m_data);}

Use:

String S3 (S1);

Here S3 is also the newly created object, it is necessary to call the constructor, the first to open up enough space, and then copy the content to be copied in, this is a deep copy, if you use the compiler default copy constructor, just copy the pointer over

    • Copy Assignment action operation

To assign the right thing to the left (Note: There is something), the normal idea is to first empty the left, and then create the same size as the right side of the space, and then copy the right content to the left, so, to achieve the following:

inline String& String::operator=(Conststring&str) {    if( This= = &str)//Self assignment or not        return* This; Delete[] m_data;//KillM_data =New Char[Strlen (Str.m_data) +1];    strcpy (M_data, str.m_data); return* This;}//UseString s4=s1;
  • output Function
     #include <iostream> #include   " string.h   " using  namespace   Std;ostream  & operator  << ( ostream& OS, const  string& str) {OS     << Str.get_c_str ();  return   OS;}  //  use  string S1 (  " hello   "  <<s1; 

    The output function must be a global function so that the left call "<<" is guaranteed

  • Summarize

Now, let's review the design of the string class, design a class, first of all , we consider what kind of data we need in class, here is the string, we have a lot of characters in the string, of course, we can easily think of using arrays to store, but, The design string is not a good choice, because the array declaration must specify the size of the array, so we select the pointer, the future of how much content, using new way to dynamically allocate size, in a 32-bit system, a pointer to 4 byte, so no matter how large the string, The object of the string itself is4byte; Then, consider the design of which functions, constructors, said before, here is not much to say, as the member is a pointer, so you need to design copy constructor, copy assignment operation function, destructor (Big three), After designing these three functions, think about what else you need to design, because we need to output the string, which requires cout, so we need to take out the characters in M_data, cout can receive this stuff, so, design Char* get_c_ STR () const {return m_data;} , just return, do not change, so designed to be const type.

The following is the complete string class for the design of the header file

1 #pragmaOnce2 #ifndef __string__3 #define__string__4#include <cstring>5 classString {6  Public:7String (Const Char* CStr =0);//construct func8     //if only the CALSS with pointer Pamater (s), we need design, functions as follow9String (Conststring& str);//copy construct func,the parameter type is Itsown typeTenstring&operator=(Conststring& str);//copy assign,the parameter is Itsown type One  A~String (); -     Char* GET_C_STR ()Const{returnm_data;} - Private: the     Char* M_DATA;//because the string is variable in length, it is set to a dynamic array-pointer - }; -  - inline +String::string (Const Char* CStr =0) - { +     if(CStr) {//with initial value AM_data =New Char[Strlen (CStr +1)]; at strcpy (m_data, CStr); -     } -     Else { -M_data =New Char[1]; -*m_data =' /'; -     } in } -  to inline +string::~String () - { the     Delete[] m_data;// Clean Up * } $ //Copy construct fuctionPanax Notoginseng inline -String::string (Conststring&str) the { +M_data =New Char[Strlen (Str.m_data) +1]; A strcpy (m_data, str.m_data); the } +  - inline $string& String::operator=(Conststring& str)//string&:& is reference $ { -     if( This= = &str)//Self assignment or not,&str:& is getting address -         return* This; the     Delete[] m_data;//Kill -M_data =New Char[Strlen (Str.m_data) +1];Wuyi strcpy (m_data, str.m_data); the     return* This; - } Wu #endif
View Code

C + + class with pointer member (s)

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.