When to customize copy constructors

Source: Internet
Author: User

A class that contains dynamic memory allocations requires a custom copy constructor. An undefined default is a shallow copy, at which point the Parameter object and the pointer member that creates the object points to the same piece of memory, the first object call frees the memory successfully when the second object is called, and the secondary objects again frees the memory, at which time the run-time error double free: should be defined and a shallow copy instance code for deep copy:
1#include <iostream>2 3 classA4 {5      Public:6 A ()7         {   8Std::cout <<"constructor is called"<<Std::endl;9n =New int[Ten];Tenn[0] =1; One         } A         //Default copy constructor -         /*A (const a &t) -         { the std::cout << "copy constructor is called" << Std::endl; - n = T.N; -         } -         */ +  -~A () +         {    AStd::cout <<"destructor is called"<<Std::endl; at delete n; -         }    -  -         void Get() {Std::cout <<"N[0]:"<< n[0] <<Std::endl;} -     Private: -         int*N; in }; -  to intMainvoid) + { - A; the a B (a); *B.Get(); $ Panax Notoginseng     return 0; -}
Post-compilation results: Deep copy Instance code:
1#include <iostream>2#include <string.h>3 4 classA5 {6      Public:7 A ()8         {   9Std::cout <<"constructor is called"<<Std::endl;Tenn =New int[Ten]; Onen[0] =1; A         }    -         //Deep Copy -AConstA &t) the         {    -Std::cout <<"copy constructor is called"<<Std::endl; -n =New int[Ten]; -memcpy (n, T.N,Ten); +         }    -  +~A () A         {    atStd::cout <<"destructor is called"<<Std::endl; - delete n; -         }    -  -         void Get() {Std::cout <<"N[0]:"<< n[0] <<Std::endl;} -     Private: in         int*N; - }; to  + intMainvoid) - { the A; * a B (a); $B.Get();Panax Notoginseng  -     return 0; the}

Compile run Result:

When to customize 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.