시작...

블로그 이미지
mutjin

Article Category

분류 전체보기 (148)
기록 (3)
개발새발 (8)
2010년 이전 글 (133)

Recent Post

Recent Comment

Recent Trackback

Calendar

«   2024/05   »
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

Archive

My Link

  • Total
  • Today
  • Yesterday

코드 내용은 MEC++ 의 항목 29[각주:1] ( 258p~266p ) 를 뱃겼다.

  1 #include <iostream>
  2
  3 class MyString {
  4   public:
  5     MyString( const char * in_str = "" ) : value( new StrValue( in_str ) ) {
  6     MyString( const MyString& rhs ) : value( rhs.value ) {
  7       ++value->refCount;
  8       printf(" init refCount : %d\n", value->refCount );
  9     }
 10
 11     ~MyString() {
 12       printf(" dest refCount : %d\n", value->refCount );
 13       if(--value->refCount == 0 ) delete value;
 14     }
 15     MyString& operator=( const MyString & rhs );
 16
 17     const char* c_str() { return value->data; }
 18
 19   private:
 20     struct StrValue {
 21       int refCount;
 22       char * data;
 23
 24       StrValue( const char * in_str ) : refCount(1)
 25       {
 26         printf( "new called\n" );
 27         data = new char[strlen(in_str) + 1];
 28         strcpy( data, in_str );
 29       }
 30       ~StrValue() {
 31         printf( "delete called\n" );
 32         delete [] data;
 33       }
 34
 35     };
 36
 37     StrValue *value;
 38 };
 39
 40 MyString& MyString::operator=( const MyString& rhs )
 41 {
 42   if( value == rhs.value ) return *this;
 43
 44   if( --value->refCount == 0 ) delete value;
 45
 46   value = rhs.value;
 47   ++value->refCount;
 48
 49   return *this;
 50 }
 51
 52 int main()
 53 {
 54   MyString s1( "abc" );
 55   printf(" 1 .......... %s \n", s1.c_str() );
 56   MyString s2(s1);
 57   printf(" 2 .......... %s \n", s2.c_str() );
 58   MyString s3;
 59   printf(" 3 .......... %s \n", s3.c_str() );
 60
 61   s3 = s2;
 62   printf(" 3-2 .......... %s \n", s3.c_str() );
 63
 64   return 0;
 65 }
 66

결과

new called
 1 .......... abc
 init refCount : 2
 2 .......... abc
new called
 3 ..........
delete called
 3-2 .......... abc
 dest refCount : 3
 dest refCount : 2
 dest refCount : 1
delete called

결과 분석
54번 라인에서 s1이 생성되면서 26라인이 출력 되었다.
56 라인에서 s2가 생성되면서 참조카운트(refCount)가 2로 증가 하였다.
58 라인에서 s3가 생성되면서 다시 26 라인이 출력되었다.
그러나 61 라인에서 s2의 값 복사가 발생해서 s3의 값(빈문자열)이 삭제되어 31 라인이 출력 되었다.
끝으로 main이 끝나며 객체가 하나씩 파괴되고 마지막으로 실제 data도 삭제된다.


[] 연산자나 포인터, 참조자 등등을 추가 해야 하지만, 책을 참조하자 ^^;



  1. 도서에 대한 내용은 http://mutjin.com/159 를 참고하자 [본문으로]

'개발새발 > 기초' 카테고리의 다른 글

getCurrentTime() 함수  (0) 2011.07.19
postgreSQL 에서 oracle의 rowid 같은 값 이용하기  (0) 2011.02.18
메모리 지정 new(placement new)  (0) 2010.04.12
parameter & argument  (0) 2010.04.09
const 정리  (0) 2010.04.02
and