Notice
Recent Posts
Recent Comments
Link
«   2025/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
Tags
more
Archives
Today
Total
관리 메뉴

IT Language 연습실

스마트 포인터 (Smart Pointer) 본문

C++

스마트 포인터 (Smart Pointer)

akongman 2024. 2. 22. 16:51

포인터 * ,  -> 도 연산자인데, 우리가 아는 포인터는 어떠한 기능이 없다.

기능 없는 포인터에 기능을 넣어 재정의 한다면 그것이 스마트 포인터인데.

본인이 알고 있는 것은 라이브러리에 정의된 스마트 포인터가 아니라 스마트 포인터를 이해하기 위한

사용법? 이해할 수 있는 발판을 지금 마련한 것인 것 같다.

 

정확한 라이브러리에 정의된 스마트 포인터에 대한 문서는 다른 문서를 참고하자.

여기서는 스마트 포인터 문법 이해해 대한 발판을 설명할 것이다.

 

참고로 스마트 포인터는 실무에 많이 쓰인다고 하는데.. 공부할 필요가 더 있을 것 같다.

 

#include <iostream>
using namespace std;

class A { 
    int x; int y;
    public : 
    A (int n, int m) : x(n), y(m) {}
    void function() { x = 5; y = 6; }
    void showPosition() { 
        int temp = x; 
        x = y;
        y = temp;
    }
    friend ostream & operator<<(ostream & os, A & ref);
};
ostream & operator<<(ostream & os, A & ref) { 
    os<<ref.x<<' '<<ref.y<<endl;
    return os;
}
template <typename T>
class Smartptr { 
    T *ptr;
    
    public :
    Smartptr(T * ref);
    T & operator*();
    T * operator->();
    ~Smartptr();
    
};
template <typename T>
Smartptr<T>::Smartptr(T * ref) : ptr(ref) {}

template <typename T>
T & Smartptr<T>::operator*() { 
     return *ptr;
}
template <typename T>
T * Smartptr<T>::operator->() { 
    return ptr;
}
template <typename T>
Smartptr<T>::~Smartptr() { 
    delete ptr;
    cout<<"삭제"<<endl;
}
int main() { 
    Smartptr<A>box1(new A(1,2));
    Smartptr<A>box2(new A(3,4));
    cout<<*box1; 
    cout<<*box2; 
    
    box2->function(); 
    
    cout<<*box2;
    
    box1->showPosition();
    cout<<*box1;
}

 

위 긴 코드가 있는데 이해하는데 어렵지 않을 것이다. 가장 핵심이 되는 부분만 콕 찝겟다. 

operator* 와 operator -> 부분이다.

'C++' 카테고리의 다른 글

C++ 스타일에 맞는 형변환  (0) 2024.02.25
template (4) 클래스 ver  (0) 2024.02.23
template 파일 분할.  (0) 2024.02.22
template (3) 클래스 ver  (0) 2024.02.22
template (2) 함수 ver  (0) 2024.02.21