프로그래밍 언어/C++
C++ 얕은 복사 깊은 복사 (Shallow/Deep Copy)
ShovelingLife
2022. 7. 29. 20:03
아래와 같이 코드를 작성하면 a1 객체와 a2 객체가 서로 같은 int형에 대한 포인터 변수를 공유하기 때문에 이미 해제된걸 재해제 하기 때문이다.
#include <iostream>
using namespace std;
class A
{
int* ptr = nullptr;
public:
A()
{
ptr = new int();
}
A(const A& Ref)
{
this->ptr = Ref.ptr;
}
~A()
{
delete ptr;
}
};
int main()
{
// 기본 생성자 호출
A a1;
// 복사 생성자 호출
A a2(a1);
}
이를 해결하기 위해선 ptr를 참조 대상값 가지고서 재 할당 해줘야한다.
#include <iostream>
using namespace std;
class A
{
int* ptr = nullptr;
public:
A()
{
ptr = new int();
}
A(const A& Ref)
{
this->ptr = new int(*Ref.ptr);
}
~A()
{
cout << "소멸자 호출" << endl;
delete ptr;
}
public:
void Set(int Val)
{
*ptr = Val;
}
void Print()
{
cout << *ptr << endl;
}
};
int main()
{
A a1;
a1.Set(5);
A a2(a1);
a1.Print();
a2.Print();
}