C++实现智能指针(四)

  • 解引用
指针的解引用可以使用*运算符和->运算符,C++语言的运算符重载机制,为我们满足上述需求提供了技术支持。
重载*运算符时其返回的应该是智能指针所指的资源对象实体, 而->运算符则应该返回的是智能指针指针所指的资源对象的内存地址
// 重载*和-> 运算符
    /*重载运算符* */
    T&  operator* () const {return *mPointer;};
    /*重载运算符-> */
    T* operator-> () const {return mPointer;};
  • 判空与比较
==和!=运算符都是必须重载两个版本:
// 方式1 智能指针与原生指针的比较
if (sp1==NULL)
if (sp1!=NULL)
if (sp1==p)
//方式2 智能指针与智能指针间的比较
if (sp1==sp2)

可以用宏来简化代码的编写:

#define COMPARE(_op_)                                           \
bool operator _op_ (const SmartPointer& o) const {              \
    return mPointer _op_ o.mPointer;                            \
}                                                               \
bool operator _op_ (const T* o) const {                         \
    return mPointer _op_ o;                                     \
}          
// 重载==
COMPARE(==)
// 重载!=
COMPARE(!=)

  • 实现智能指针v4  smartpointer.h
/* 
* file name : smartpointer.h
* desp : 智能指针版本v4
*/
#ifndef __SMARTPOINTER_H__
#define __SMARTPOINTER_H__

#define COMPARE(_op_)                                           \
bool operator _op_ (const SmartPointer& o) const {              \
    return mPointer _op_ o.mPointer;                            \
}                                                               \
bool operator _op_ (const T* o) const {                         \
    return mPointer _op_ o;                                     \
} 

template <typename T>  // 将智能指针类定义成模板类
class SmartPointer {
public:
    // 默认构造函数
    SmartPointer():mPointer(NULL) {std::cout <<"Create null smart pointer."<< std::endl;}   
 // 接收不同对象类型的构造函数
    SmartPointer(T *p):mPointer(p) {
        std::cout <<"Create smart pointer at "<<static_cast<const void*>(p)<<std::endl;
        /*智能指针指向类T,引用计数加1*/
        if (mPointer) mPointer->incRefCount();
    }     
    // 析构函数
    ~SmartPointer(){
        std::cout << "Release smart pointer at "<<static_cast<const void*>(mPointer)<<std::endl;
        // 实现内存资源自动销毁机制
        if (mPointer && mPointer->decRefCount()==0) delete mPointer;
    }
    // 拷贝构造函数
    SmartPointer(const SmartPointer &other):mPointer(other.mPointer) {
        std::cout <<"Copy smart pointer at "<<static_cast<const void*>(other.mPointer)<<std::endl;
       // 引用计数加1
       if(mPointer) mPointer->incRefCount();
    }     
   // 赋值操作符         
   SmartPointer &operator = (const SmartPointer &other) {
       T *temp(other.mPointer);
       // 新指向对象,引用计数值加1
       if (temp) temp->incRefCount();
       // 原指向对象,引用计数值减1,如果减1后引用计数为0 销毁原资源对象
       if (mPointer && mPointer->decRefCount()==0) delete mPointer;
       // 智能指针指向新资源对象
       mPointer = temp;  
       return *this;
   } 

   // 重载*和-> 运算符
    /*重载运算符* */
    T&  operator* () const {return *mPointer;}
    /*重载运算符-> */
    T* operator-> () const {return mPointer;}

    // 判空与比较

    COMPARE(==);
    COMPARE(!=);
private:
    T *mPointer; // 指向智能指针实际对应的内存资源,根据参数自动推导规则,定义内部资源指针类型
};

/*引用计数基类*/
class RefBase   
{   
    public:   
        RefBase() : mCount(0){ }   
        void incRefCount(){   
            mCount++;   
        }   
        int decRefCount(){   
            return --mCount;
        }   
        // 调试接口,返回对象当前引用计数   
        int getRefCount() const {   
            return mCount;   
        }  

        virtual ~RefBase(){};
    private:   
        int mCount;   
};   
#endif // __SMARTPOINTER_H__

  • 测试代码:aptestcase4.cpp
/* 
* file name : sptestcase4.cpp
* desp : 智能指针测试代码 case4 测试智能指针的解引用、判空及比较功能
*/

#include <iostream>
#include "smartpointer.h"

/*继承于引用计数基类的SomeClass类*/
class SomeClass: public RefBase{
public:
    SomeClass(){std::cout << "SomeClass default constructor !"<<std::endl;}
    ~SomeClass(){std::cout << "SomeClass deconstructor !"<<std::endl;}
    void func(){std::cout << "SomeClass func()" <<std::endl;}
};

/*继承于引用计数基类的OtherClass类*/
class OtherClass: public RefBase{
public:
    OtherClass(){std::cout << "OtherClass default constructor !"<<std::endl;}
    ~OtherClass(){std::cout << "OtherClass deconstructor !"<<std::endl;}
    void foo(){std::cout << "OtherClass foo()" <<std::endl;}
};

// 解引用测试
void testcase4_1(void)
{
    std::cout << "=======testcase4_1=========" <<std::endl;
    SmartPointer<SomeClass> spsomeclass = new SomeClass();
    (*spsomeclass).func();
    spsomeclass->func();
    std::cout << "==========================" <<std::endl;
}

// 判空与比较测试
void testcase4_2(void)
{
    std::cout << "=======testcase4_2=========" <<std::endl;
    SomeClass *psomeclass = new SomeClass();
    SmartPointer<SomeClass> spsomeclass = psomeclass;

    SmartPointer<OtherClass> spotherclass = new OtherClass();
    SmartPointer<OtherClass> spotherclass2 = spotherclass;

    if (spsomeclass == NULL) std::cout<< "spsomeclass is NULL pointer" << std::endl;
    if (spotherclass != NULL) std::cout<< "spotherclass is not NULL pointer" << std::endl;
    if (spsomeclass == psomeclass)  
       std::cout<< "spsomeclass and psomeclass are same pointer" << std::endl;
    if (spsomeclass != psomeclass)  
       std::cout<< "spsomeclass and psomeclass are not same pointer" << std::endl;
//     if (spsomeclass != spotherclass) // ERROR !
//        std::cout<< "spsomeclass and spotherclass are not same pointer" << std::endl;
//     if (spsomeclass == spotherclass) // ERROR !
//        std::cout<< "spsomeclass and spotherclass are same pointer" << std::endl;
    if (spotherclass == spotherclass2) std::cout<< "spotherclass and spotherclass2 are same pointer" << std::endl;
    if (spotherclass != spotherclass2) std::cout<< "spotherclass and spotherclass2 are not same pointer" << std::endl;    
    std::cout << "==========================" <<std::endl;

}

int main(void)
{
    testcase4_1();
    testcase4_2();
    return 0;
}
  • 结果分析

猜你喜欢

转载自blog.csdn.net/qq_32274259/article/details/80199936
今日推荐