Instagram
Recent Posts
Recent Comments
«   2026/10   »
일 월 화 수 목 금 토
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
more
Archives
Today
Total
관리 메뉴

기록중

[C++] 얕은 복사 정책에 대한 방안 4가지. 본문

Study/C\C++

[C++] 얕은 복사 정책에 대한 방안 4가지.

코튼아 2016. 2. 23. 16:44
      //기본 생성자
       Person(const char* n, int a) : age(a) {
		name = new char[strlen(n) + 1];
		strcpy(name, n);
		cout << "Person(const char n, int a)" << endl;
	}
	//기본 복사 생성자는 "얕은 복사"를 한다.
	Person(const Person &o) : name(o.name), age(o.age) {
		cout << "~S Person(), delete[] name" << endl;
	};



1. 깊은 복사 : 성능이 낮아짐.

	//기본 복사 생성자의 "깊은 복사"를 해보자?
	Person(const Person &o) : age(o.age) { // 1. 값은 얕은 복사 후
                //2. 포인터는 깊은 복사를 수행
		name = new char[strlen(o.name) + 1];
		strcpy(name, o.name);		
		cout << "DEEP Person()" << endl;
	};

2. 복사 금지 : 복사 생성자를 private로 옮기면 끝!

사용자가 복사를 하고자 할 때 컴파일 Error 발생한다.

private:
	Person(Person & o) {};

3. 소유권 이전 : 소유권을 이전해 준 녀석의 객체에 대해서는 사용하지 않는다. 무책임해!

auto_ptr 방식임

      //인자의 타입을 비상수화 시키는 것이 핵심이다.
       Person(Person &o) : age(o.age), name(o.name) { //1. 얕은 복사 후,
		//2. 소유권을 끊어낸다.
		o.name = "";
		o.age = 0;
	};

4. C++ 11의 "shared_ptr"와 "unique_ptr"

#include 

int main() {
	shared_ptr p(new Person("daniel", 10));
	cout << " 참조하고 있는 포인터의 수 : " << p.use_count() << endl;
	shared_ptr q = p; //Person q(p); 선언과 동시에 초기화 될 경우, 복사 생성자가 호출 됨
	cout << " 참조하고 있는 포인터의 수 : " << q.use_count() << endl;
}

참조 계수 기반으로 작성해보기 : 성능이 좋음 :D

//참조 계수 동적 할당을 위한 포인터
private:
	int* ref;
//참조 계수 기반의 복사 생성자
public:
	Person(const Person& o) : name(o.name), age(o.age), ref(o.ref) { //1. 모든 변수를 얕은 복사 후
		// 2. 참조 계수만 증분한다.
		++(*ref);
	}
//참조 계수 기반의 소멸자
~Person() {
		if (--(*ref) == 0) {
			delete[] name;
			delete ref;
		}
	}

Comments