Discussion on the issues arising from the default copy constructor of C ++

Source: Internet
Author: User

I mentioned the copy constructor in my previous blog. However, it is hard to understand the copy constructor in some cases. So let's discuss the copy constructor.
 

The copy constructor is dividedShortest copyAndDeep copy: the default copy constructor is a light copy.

By default, the copy constructor copies the memory space of the old object to the memory space of the new object.

If the class has a pointer type, the default copy constructor can only copy the value of the pointer property, but cannot copy the memory pointed to by the pointer property.At this time, if we do not explicitly define the copy constructor, we may encounter very strange problems during programming.

Explicitly define the copy constructor to copy pointer properties and other properties that require special processing.

The Number one: Let's first look at The problems caused by The shallow copy.

--------------------- I am a split line ------------------------

 
 
  1. # Include <iostream>
  2. Using namespace std;
  3. Class Car
  4. {
  5. Private:
  6. Char * brand;
  7. Float price;
  8. Public:
  9. Car (const char * sz, float p)
  10. {
  11. // The constructor allocates memory for the brand.
  12. Brand = new char [strlen (sz) + 1];
  13. Strcpy (brand, sz );
  14. }
  15. ~ Car
  16. {
  17. // Release the applied memory in the destructor
  18. Delete [] brand;
  19. Cout <"Clear is over! "<Endl;
  20. }
  21. Void just_print ()
  22. {
  23. Cout <"brand:" <brand <endl;
  24. Cout <"price:" <price <endl;
  25. }
  26. };
  27. Int main (void)
  28. {
  29. Car_one ("BMW", 120 );
  30. Car_one.just_print ();
  31. // Call the default copy constructor
  32. Car car_two (comp_one );
  33. Car_two.print ();
  34. Return 0;
  35. }

----------------------------------------------------------------------------
 

This program failed. Code Analysis:

1. car_two (car_one) is equivalent

Car_two.brand = car_one.brand;

Car_two.price = car_one.price;

2. After the assignment operation, the pointers in the two objects point to the same dynamic memory. When car_one and car_two are revoked, the function to release the same dynamic memory must be released. However, after two objects are undo first, once one object is undo, the brand pointer of the other object changes to "Wild Pointer". Using this pointer to release the same dynamic memory will cause a memory error.

Not only is the memory released repeatedly, but other problems may occur:

-------------------------------------------------------------------------------

 
 
  1. Int main (void)
  2. {
  3. Car car_one ("Dell", 7000 );
  4. If (true)
  5. {
  6. Car car_two (car_one );
  7. Car_two.print ();
  8. }
  9. // The dynamic memory pointed to by car_one.brand has been released.
  10. Car_one.print ();
  11. Return 0;
  12. }

Bytes -------------------------------------------------------------------------------------------

Because car_two is a local object defined in the if structure, when the if structure exits, car_two is revoked and the system automatically calls its destructor to release the dynamic memory pointed to by car_two.brand, because the car_one and car_two values are the same, car_one.brand has no fingers and becomes a wild pointer. In this case, read/write operations on the pointer will cause unexpected errors.

----------------------------------------------------------------------------

In this case, we need to define the copy constructor by ourselves:

----------------------------------------------------------------------------

 
 
  1. // Explicitly define the constructor
  2. # Include <iostream>
  3. # Include <cstring>
  4. Using namespace std;
  5. Class Car
  6. {
  7. Private:
  8. Char * brand;
  9. Float price;
  10. Public:
  11. Car (const char * sz, float p)
  12. {
  13. Brand = new char [strlen (sz) + 1];
  14. Strcpy (brand, sz );
  15. Price = p;
  16. }
  17. // Custom copy constructor
  18. Car (const Car & cp)
  19. {
  20. // Re-create a memory space of the same size as cp. brand for brand
  21. Brand = new char [strlen (cp. brand) + 1];
  22. //
  23. Strcpy (brand, cp. brand );
  24. Price = cp. price;
  25. }
  26. ~ Car ()
  27. {
  28. Delete [] brand;
  29. Cout <"clear over" <endl;
  30. }
  31. Void print ()
  32. {
  33. Cout <"brand" <endl;
  34. Cout <"price" <endl;
  35. }
  36. };
  37. Int main (void)
  38. {
  39. Car car_one ("Dell", 8999 );
  40. Car_one.print ();
  41. //
  42. Car car_two (car_one );
  43. Car_two.print ();
  44. // The user does not directly assign values using brand = cp. brand, but re-applies for dynamic memory.
  45. // The database function strcpy copies strings.
  46. // Car_one.brand and car_two.brand point to two different memories to avoid errors.
  47. Return 0;
  48. }

Bytes ------------------------------------------------------------------------------------------

Finally, we recommend that you reload the operator = operator for a custom copy constructor!

Bytes -----------------------------------------------------------------------------------------

51cto blog: http://liam2199.blog.51cto.com/2879872/1417892

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.