C + + pointer hanging (assignment operator overloading)

Source: Internet
Author: User

Such as:

String A ("Sky1"), B ("Sky2");

b = A;

The program creates two objects at run time, A and B, respectively, and then calls the constructor. When executing "b=a", because there is no user-defined assignment operator function, then the program automatically calls the default assignment function, two pointers to the same memory, "Sky2" the memory of this space should be inaccessible. When the program executes to the destructor, releases the memory, revokes b, releases the memory that B points to, and then releases a, however, although the pointer to a is still in, however, because it is the same memory as the B point, and because the memory space of "Sky1" is released when the destructor B is executed, now execution A is released, Unable to find the memory to be freed, and the memory that the previous B pointed to has not been released, the destructor cannot find where it is? There is the so-called "pointer hanging Problem".

Resolved as follows:

#include <iostream>#include<string.h>using namespacestd;classstring{ Public: String (intSize =1,Char* str =" /") {ptr=New Char[size];        strcpy (PTR,STR);  This->size =size; } String (ConstString &obj) {Size=obj.size; PTR=New Char[size];     strcpy (PTR,OBJ.PTR); } Stringoperator=(ConstString & obj)//avoid the problem of pointer hanging{size=obj.size; delete [] ptr;//release the original memory firstPTR =New Char[Size];//to generate new memorystrcpy (PTR,OBJ.PTR);//Copy String          return* This; }     ~String () {delete [] ptr; }Private :    Char*ptr; intsize;};intMain () {String str1 (Ten,"Hangzhou"), STR2 (Ten,"HDU"); STR2= STR1;//easy to cause the needle to hang    return 0;}

C + + pointer hanging (assignment operator overloading)

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.