언어/C++

[C++] 얕은 복사, 깊은 복사

study_memo 2023. 9. 25. 18:31

깊은 복사 = 값 복사

얕은 복사 = 주소값 복사

 

 

문제: 위 코드는 복사 생성자의 얕은 복사로 인하여 두 객체가 이어진 상태이다. 이를 보이지 않는 복사 생성자를 고쳐서 깊은 복사로 만들어보자.

#include <iostream>
using namespace std;


class SelfRef
{
private:
	int *num;
public:
	SelfRef(int n) : num(new int(n))
	{
		cout << "객체생성" << endl;
	}
	void setNumber()
	{
		*num += 1;
	}
	void ShowTwoNumber()
	{
		cout << *num << endl;
	}
};

int main(void)
{
	SelfRef obj(3);
	SelfRef obj2(obj);

	obj.setNumber();

	obj.ShowTwoNumber();
	obj2.ShowTwoNumber();
	return 0;
}

 

#include <iostream>
using namespace std;


class SelfRef
{
private:
    int* num;
public:
    SelfRef(int n) : num(new int(n))
    {
        cout << "객체생성" << endl;
    }
    SelfRef(const SelfRef& obj) {
        num = new int(*obj.num);  //*(obj.num)이거임.. (*obj).num이 아니고..
    }
    void setNumber()
    {
        *num += 1;
    }
    void ShowTwoNumber()
    {
        cout << *num << endl;
    }
};

int main(void)
{
    SelfRef obj(3);
    SelfRef obj2(obj);

    obj.setNumber();

    obj.ShowTwoNumber();
    obj2.ShowTwoNumber();
    return 0;
}

 

복사생성자(얕은복사)를 이용하라하면..?

#include <iostream>
using namespace std;


class SelfRef
{
private:
    int* num;
public:
    SelfRef(int n) : num(new int(n))
    {
        cout << "객체생성" << endl;
    }
    //모든 디폴트 복사 생성자는 얕은 복사이다. -> 주소 복사
    SelfRef(const SelfRef& a) {
        num = a.num; 
    }
  
    void setNumber()
    {
        *num += 1;
    }
    void ShowTwoNumber()
    {
        cout << *num << endl;
    }
};

int main(void)
{
    SelfRef obj(3);
    SelfRef obj2(obj);

    obj.setNumber();

    obj.ShowTwoNumber();
    obj2.ShowTwoNumber();
    return 0;
}