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;
}
  • 结果分析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值