C++:CopyConstructors
C++의 복사 생성자.
Example
아래와 같은 예를 만들 수 있다.
#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;
}
위와 같은 경우 a1.ptr
과 a2.ptr
은 동일한 Pointer를 가리키고 있기 때문에(얕은 복사) 두 번의 소멸자가 호출되는 시점에 프로그램이 죽게 된다.
실행하면 아래와 같이 죽는다.
$ ./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: 기본 생성자에 대한 설명.
- C++:virtual
- 얕은 복사 (Shwallow Copy)
- 깊은복사 (Deep Copy)