C++:CopyConstructors
lastmod 2025-02-14created 2017-01-164 edits
Copy constructors in C++.
Example
You can create an example like the one below.
#include <iostream>
using namespace std;
struct A
{
int * ptr;
A(int a) { ptr = new int(a); }
~A() { delete ptr; }
};
int main()
{
A a1(100);
A a2 = a1;
return 0;
}
In the case above, a1.ptr and a2.ptr point to the same Pointer (shallow copy), so the program crashes when the destructor is called twice.
When run, it crashes as shown below.
$ ./a.out
a.out(62678,0x7fffc1a733c0) malloc: *** error for object 0x7fb914c02790: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
See also
- C++:DefaultConstructors: an explanation of default constructors.
- C++:virtual
- Korean: 얕은 복사 (Shwallow Copy)
- Korean: 깊은복사 (Deep Copy)