A question about copying Constructors

Source: Internet
Author: User

If the programmer does not define a copy constructor, the compiler automatically generates a default copy constructor. What problems may arise?

The following is an example

1. No copy constructor

# Include <iostream>

Class myclass
{
Public:
Myclass (int)
{
B = new int ();
}
Int * myget ()
{
Return B;
}
Protected:
PRIVATE:
Int * B;
};

 

Int main ()
{
Myclass class1 (5 );
Myclass class2 (class1 );
STD: cout <"class1. B =" <class1.myget () <"<" * B = "<* (class1.myget () <STD :: endl;
STD: cout <"class1. B =" <class2.myget () <"<" * B = "<* (class2.myget () <STD :: endl;
}

Execution result:

That is, the data members of two objects Save the same memory address.

 

2. copy constructor (deep copy)

# Include <iostream>

Class myclass
{
Public:
Myclass (int)
{
B = new int ();
}
Myclass (const myclass & class2)
{
B = new int (* (class2. B ));
}
Int * myget ()
{
Return B;
}
Protected:
PRIVATE:
Int * B;
};

 

Int main ()
{
Myclass class1 (5 );
Myclass class2 (class1 );
STD: cout <"class1. B =" <class1.myget () <"<" * B = "<* (class1.myget () <STD :: endl;
STD: cout <"class1. B =" <class2.myget () <"<" * B = "<* (class2.myget () <STD :: endl;
}

Execution result:

That is, the data members of two objects are different, but the saved values are 5.

 

 

A: The default copy constructor is a shortest constructor. When an object contains pointer data members and uses it to initialize another object of the same type, the default copy constructor can only copy the value of the data member of the object to another object, rather than copying the entire object. In this way, the same memory unit may be released twice, causing program running errors.

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.