C + + Self-study Note _ copy constructor _ C + + Primer

Source: Internet
Author: User

In a built-in data type, you can typically initialize another variable with one variable. similarly , for objects of class type, you can also initialize another object with one object, and the compiler will synthesize a copy constructor.

#include <iostream>using namespacestd;classpoint{ Public: Point (intx=0,inty=0): XPos (x), YPos (y) {}voidPrintpoint () {cout<<"XPos:"<<xPos<<Endl; cout<<"YPos:"<<yPos<<Endl; }Private:    intXPos; intYPos;};intMain () {Point M (Ten, -); Point N=M;   N.printpoint (); //initializing an object with Object m n    return 0;}

Results of the compilation run:

XPos:yPos:0 (0x0)   0.191   Continue.

Statement point N = M; can also be  written as Point N (M); When the copy constructor is not explicitly defined in the class, the compiler defaults to a default copy constructor , also known as a copy constructor, that is the prototype of the function:

Const point&);

You can also think of a copy constructor as a normal constructor, except that the formal parameters of the function are different. The formal parameter of its copy constructor is the reference type of the object of this type.

The default copy constructor is insufficient:

Some cases must be shown to define the copy default constructor, for example:

#include <iostream>#include<cstring>using namespacestd;classbook{ Public: Book (Const Char*name) {BookName=New Char[Strlen (name) +1];//use new to request strlen (name) +1 size spacestrcpy (bookname,name); }    ~Book () {delete []bookname; //free space for the request    }    voidShowName () {cout<<"bookname="<<bookName<<Endl; }Private:    Char*bookname;};intMain () {Book CPP ("C + + Primer"); Book T=cpp;//Initialize T with CPPCpp.showname (); CPP.~book ();//manually delete the memory space occupied by the CPP objectT.showname (); return 0;}

Results after the compilation run:

bookname=c++ primerbookname=0 (0x0)   0.317   Continue.
After using the CPP object to initialize the T object, the BookName property of the T object is theoretically "C + + Primer", but it is normal for the output of the BookName property of the CPP object, and the T object's B Ookname output has a problem, the correct case should also be "C + + Primer", but this time the output is garbled.

This is the disadvantage of the default copy constructor: Restore the implementation of the default copy constructor generated by the compiler:

Book::book (const book& obj) {    bookname=obj.bookname;}

As you can see, when you initialize a T object with a CPP object, the default copy constructor simply assigns the bookname of the CPP object to the BookName of the T object, in other words, only the spatial address that the bookname of the CPP object points to T BookName, so that the bookname of the T object and the BookName of the CPP object point to the same deposit element, and when the CPP object calls the destructor, the memory unit that the CPP BookName points to is freed because the T object The bookname of the BookName and CPP object points to the same memory, so the memory that the T object BookName points to becomes an illegal content that is not available (because it has been freed), so the output is inevitably caused by an output error when the directed memory is released.

In general, it is best to manually explicitly define a copy constructor to avoid this problem when the class contains a pointer-type data member and needs to use dynamic memory.

Display definition copy default constructor
#include <iostream>#include<cstring>using namespacestd;classbook{ Public: Book (Const Char*name) {BookName=New Char[Strlen (name) +1];//use new to request strlen (name) +1 size spacestrcpy (bookname,name); } Book (Constbook&obj) {BookName=New Char[Strlen (Obj.bookname) +1];    strcpy (Bookname,obj.bookname); }    ~Book () {delete []bookname; //free space for the request    }    voidShowName () {cout<<"bookname="<<bookName<<Endl; }Private:    Char*bookname;};intMain () {Book CPP ("C + + Primer"); Book T=cpp;//Initialize T with CPPCpp.showname (); CPP.~book ();//manually delete the memory space occupied by the CPP objectT.showname (); return 0;}

Compile run Result:

bookname=c++ primerbookname=c++0 (0x0)   0.315   Continue.

In this example, we explicitly define a copy constructor in place of the default copy constructor, in the function body of the copy constructor, instead of assigning the address of the source object to the initialized object directly, and then copying the properties of the source object when you request a memory independently, then the CPP object's The bookname of the bookname with the T object is to point to two different memory units, so that the object T initialized after the source object CPP is destroyed will no longer be affected.

C + + Self-study Note _ copy constructor _ C + + Primer

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.