C + +: Default copy constructor performs shallow copy

Source: Internet
Author: User
Tags constructor copy shallow copy

C + +, a copy constructor is generated by default, and when a pointer appears in a class, the copy performs a shallow copy, that is, only the address of the pointer is copied, and the data is not copied;

So in class, when using pointers, you need to be aware of; If you want to use a deep copy, you can add a copy constructor.

The following code, if you do not add a copy constructor, will run an error, but you can compile,

At runtime, the program cannot execute because deletion (delete[]) is two times the same address space as Str refers to.

Code:

* * * main.cpp * * Created on:2014.4.15 * author:spike//*vs2012*/#include <iostream  
      
> #include <cstring> #include <vector> #include <memory> using namespace std;  
    Class CDemo {Public:cdemo (): Str (NULL) {};  
        ~cdemo () {static int i=0; if (str) {std::cout << "&demo" << i++ << "=" << (int*) this <<, str =  
            "<< (int*) str << Std::endl;  
        Delete[] STR;  
        }///copy constructor CDemo (const cdemo& CD) {this->str = new Char[strlen (CD.STR) + 1];  
    strcpy (This->str, CD.STR);  
} char* str;  
      
};  
    int main () {CDemo D1;  
    D1.STR = new CHAR[32];  
    strcpy (D1.str, "Caroline");  
    std::vector<cdemo>* A1 = new std::vector<cdemo> (); A1->push_back (D1); Perform a copy constructor std::cout << "D1.str =" << d1.str << Std::endl;  
    Std::cout << "(*a1) [0].STR =" << (*A1) [0].str << Std::endl;  
    strcpy (D1.str, "Wendy");  
    Std::cout << "d1.str =" << d1.str << Std::endl;  
    Std::cout << "(*a1) [0].STR =" << (*A1) [0].str << Std::endl;  
    Delete A1;  
return 0; }

Output:

D1.str = Caroline  
(*a1) [0].str  = Caroline d1.str  
= Wendy  
(*A1) [0].str  = Wendy  
&demo0 = 0x312570, str = 0x312548  
&demo1 = 0x22fec8, str = 0x312548

Author: csdn Blog spike_king

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

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.