chyam

[c++] - 얕은 복사, 깊은 복사 본문

카테고리 없음

[c++] - 얕은 복사, 깊은 복사

chyam_eun 2025. 4. 10. 13:28

얕은 복사 

  • 값을 복사하는게 아니라, 변수가 가진 메모리 주소를 복사합니다. 
class Student {
public:
    char* name;
    int age;

    Student(const char* n, int a) {
        name = new char[strlen(n) + 1];
        strcpy(name, n);
        age = a;
    }
}

Student s1 = Student("Kim", 18);
Student s2 = s1;
 
cout << s1.name << " " << s1.age << endl;
delete[] s1.name;
cout << s2.name << " " << s2.age << endl; // s2.name에는 이상한값이 출력된다.

발생할 수있는 문제점?

  • s1에서 name을 제거 한뒤, s2의 name에 접근하려한다면 delete된 힙 공간에 접근하는 문제가 발생합니다.
  • 어느 한 곳에서 값을 변경하면 변경된 값이 모두에게 적용됩니다. 같은 메모리 공간을 참조하고있기 때문입니다.

깊은 복사

  • 포인터 변수가 서로 다른 메모리 공간을 참조합니다.
class Student {
public:
    char* name;
    int age;

    Student(const char* n, int a) {
        name = new char[strlen(n) + 1];
        strcpy(name, n);
        age = a;
    }
    
	Student(const Student& s)
	{
		name = new char[strlen(s.name) + 1];
		strcpy(name, s.name);
		age = s.age;
	}
}
...

Student s1 = Student("Kim", 18);
Student s2 = s1;
 
strcpy(s1.name, "Lee");
cout << s1.name << " " << s1.age << endl; // Lee 18
cout << s2.name << " " << s2.age << endl; // Kim 18
  • 값을 변경해도 영향을 미치지 않습니다.
  • s1.name을 delete해도 에러가 발생하지 않습니다.