一顶级软件公司面试,要写一个智能指针,面试官说写一个最简单的就行了,不要用引用计数。
关键在几个指针运算符的重载,&和->都是返回指针, *返回指针的引用,因为是左值。
template <class T>
class smart_pointer
{
public:
smart_pointer(T *ptr = NULL):m_ptr(ptr)
{
}
~smart_pointer()
{
cout<<"destructor"<<endl;
delete m_ptr;
m_ptr = NULL;
}
operator T*()//指针强制类型转换 conversion
{
return m_ptr;
}
T& operator*()
{
return *m_ptr;
}
T** operator&()
{
assert(NULL == m_ptr);
return &m_ptr;
}
T* operator->();
T* operator->() const;
private:
T *m_ptr;
};
template<class T>
T* smart_pointer<T>::operator ->()
{
return m_ptr;
}
template<class T>
T* smart_pointer<T>::operator ->() const
{
return m_ptr;
}
class AAA
{
public:
int a;
AAA():a(10){}
void foo()
{
cout<<a<<endl;
}
};
int main(int argc, char* argv[])
{
const smart_pointer<AAA> ptr1(new AAA()); // if no T* operator->() const, it will fail when compiling
smart_pointer<AAA> ptr(new AAA());
void *p = (void*) ptr; // if no operator T*(), it will fail when compiling
AAA *p1 = (AAA*) ptr; // if no operator T*(), it will fail when compiling
ptr->foo();
return 0;
}