+ Reply to Thread
Results 1 to 2 of 2

Thread: What is smart pointer in C++?

  1. #1

    What is smart pointer in C++?

    What is smart pointer in C++?

    Please give me simple example of using it.

    Thanks.

  2. #2
    Smart pointer is a pointer which can automatically delete the pointer it points to when it goes out-of the scope.

    It also provides services routines so that you can use "->" and "*".

    Example:

    Code:
    template <typename T>
    class CSmartPointer
    {
    private:
    	T *m_P ;
    public:
    	explicit CSmartPointer(T *p = NULL) : m_P(p)
    	{
    	}
    
    	~CSmartPointer()
    	{
    		delete m_P ;
    	}
    
    	T& operator *()
    	{
    		return &m_P ;
    	}
    
    	T* operator ->()
    	{
    		return m_P ;
    	}
    } ;
    
    
    void UseSmaprtPointer()
    {
    	CSmartPointer<CStudent> objSmaprtPointer(new CStudent(1)) ;
    }
    Above example shows that smart pointer automatically delete the CStudent object.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts