C,C++/CONCEPT

C++ Chapter 05. 복사 생성자(Copy Constructor). 05-2 '깊은 복사'와 '얕은 복사'

너래쟁이 2018. 2. 28. 18:26


C++ Chapter 05. 복사 생성자(Copy Constructor). 


05-2 '깊은 복사'와 '얕은 복사'


* 디폴트 복사 생성자의 문제점

// 얕은 복사(shallow copy) : 디폴트 복사 생성자는 멤버 대 멤버를 단순히 복사만한다.

// 복사의 결과로 하나의 문자열을 두 개의 객체가 동시에 참조하는 꼴을 만든다 (얕은 복사)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cstring>
using namespace std;
 
class Person
{
    char * name;
    int age;
public:
    Person(char * myname, int myage)
    {
        int len=strlen(myname)+1;
        name=new char[len];
        strcpy(name, myname);
        age=myage;
    }
    void ShowPersonInfo() const
    {
        cout<<"이름: "<<name<<endl;
        cout<<"나이: "<<age<<endl;
    }
    ~Person()
    {
        delete []name;
        cout<<"called destructor!"<<endl;
    }
};
 
int main(void)
{
    Person man1("Lee dong woo"29);
    Person man2=man1;
    man1.ShowPersonInfo();
    man2.ShowPersonInfo();
    return 0;
}
cs



* '깊은 복사'를 위한 복사 생성자의 정의

// 깊은복사(deep copy) : 멤버뿐만 아니라, 포인터로 참조하는 대상까지 깊게 복사한다는 뜻

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <cstring>
using namespace std;
 
class Person
{
    char * name;
    int age;
public:
    Person(char * myname, int myage)
    {
        int len=strlen(myname)+1;
        name=new char[len];
        strcpy(name, myname);
        age=myage;
    }
    Person(const Person& copy)
        : age(copy.age)
    {
        name=new char[strlen(copy.name)+1];
        strcpy(name, copy.name);
    }
    void ShowPersonInfo() const
    {
        cout<<"이름: "<<name<<endl;
        cout<<"나이: "<<age<<endl;
    }
    ~Person()
    {
        delete []name;
        cout<<"called destructor!"<<endl;
    }
};
 
int main(void)
{
    Person man1("Lee dong woo"29);
    Person man2=man1;
    man1.ShowPersonInfo();
    man2.ShowPersonInfo();
    return 0;
}
cs