About C + + copy constructors

Source: Internet
Author: User

The copy constructor is called when the object of the class needs to be copied. The copy constructor is called in the following cases:
(1) An object is passed into the function body in the way of value passing
(2) An object is returned from the function in the way that the value is passed
(3) An object needs to be initialized by another object.

Deep if a class has resources, when the object of this class has a replication process, the resource is redistributed, the process is a deep copy, and conversely, no redistribution of resources, is a shallow copy.

If a shallow copy is applied, the value in the object is completely copied to another object, such as A=b. At this point, if a member variable pointer in B has already applied for memory, that member variable in a also points to the same piece of memory. There is a problem: when B releases the memory (for example, a destructor), a pointer inside a is a wild pointer, and a run error occurs.

1 //Shallow Copy2#include <iostream>3 using namespacestd;4  5 classCexample {6 Private:7     intA;8  Public:9Cexample (intb)Ten{a=b;} One       ACexample (Constcexample&C) -     { -A=C.A; the     } -     voidShow () -     { -cout<<a<<Endl; +     } - }; +   A intMain () at { -Cexample A ( -); -Cexample b=A; - b.show (); -     return 0; -}
1 //Deep Copy2#include <iostream>3 using namespacestd;4 classCA5 {6     Public:7CA (intBChar*CStr)8 {9A=b;TenStr=New Char[b]; One strcpy (STR,CSTR); A } -DAOConstca&C) - { theA=C.A; -Str=New Char[A]; -      if(str!=0) - strcpy (STR,C.STR); + } -     voidShow () + { Acout<<str<<Endl; at } -~CA () - { -      Deletestr; - } -    Private: in     intA; -     Char*str; to }; +   - intMain () the { *CA A (Ten,"hello!"); $CA b=A;Panax Notoginseng b.show (); -    return 0; the}

About C + + copy constructors

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.