Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 회전 및 자리 이동 연산
- LAN의 분류
- 값/참조/주소에 의한 전달
- 원형 연결 구조 연결된 큐
- r-value참조자
- 괄호 검사 프로그램
- 알고리즘 조건
- 프로그래머스 푸드 파이트 대회
- l-value참조자
- 문제해결 단계
- const l-value참조자
- C언어 덱
- getline()함수
- 네트워크 결합
- C언어 계산기 프로그램
- 문자형 배열
- string유형
- 주기억장치
- 백준 파이썬
- auto 키워드
- 입출력 관리자
- 프로그래머스 배열만들기4
- 유형 변환
- 범위 기반 for문
- C언어 스택 연산
- 운영체제 기능
- const화
- c언어 괄호검사
- IPv4 주소체계
- 논리 연산
Archives
- Today
- Total
chyam
[c++] - 얕은 복사, 깊은 복사 본문
얕은 복사
- 값을 복사하는게 아니라, 변수가 가진 메모리 주소를 복사합니다.
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해도 에러가 발생하지 않습니다.