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