Why is there a smart pointer
For C / C + + programs, there is always a mystery, that is, memory leakage. This project must use pointers. In order to facilitate the subsequent development of the program, first establish a class of intelligent pointer. This category should meet the following requirements:
-
- At the end of the pointer’s life cycle, the memory pointed to by the pointer is also released
-
- A space can only be represented by one pointer
-
- Eliminate pointer operation
2 design scheme
- Make use of the function of C + + language to make a class of C + +. At the end of the pointer class’s life, space is released in the destructor.
- 2 use object to simulate the behavior of native pointer. For example, overloaded pointer feature operators’ – > ‘and
3 code implementation
Contents of category 3.1
-
Overload the ‘*’ and ‘- >’ operators to realize the basic operation function of pointer.
T& operator * (); T* operator -> ();
-
Design copy constructor and overload of ‘=’ to realize the requirement that a piece of memory has only one pointer identifier.
SmartPointer<T>& operator = (const SmartPointer<T>& obj ); SmartPointer( const SmartPointer<T>& obj );
3.2 class implementation
template< typename T>
class SmartPointer
{
protected:
T* m_pointer;
public:
SmartPointer( T* p=nullptr )
{
m_pointer = p;
}
SmartPointer( const SmartPointer<T>& obj )
{
m_pointer= obj.m_pointer;
const_cast< SmartPointer<T>& >( obj).m_pointer =nullptr;
}
SmartPointer<T>& operator = (const SmartPointer<T>& obj)
{
if( this != &obj)
{
delete m_pointer;
m_pointer= obj.m_pointer;
const_cast<const SmartPointer<T>& >( obj).m_pointer =nullptr;
}
return *this;
}
T& operator * ()
{
return *m_pointer;
}
T* operator -> ()
{
return m_pointer;
}
bool isNull()
{
return (m_pointer == nullptr) ;
}
T* getPointer()
{
return m_pointer;
}
~SmartPointer()
{
delete m_pointer;
}
};