C++ 可以这样定义?

bandaoyu bandaoyu 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
学习智能指针,看到下面这个部分:

/* 
* file name : smartpointer.h
* desp : 智能指针版本v3
*/
#ifndef __SMARTPOINTER_H__
#define __SMARTPOINTER_H__

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;
}

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

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


class SmartPointer 定义在class RefBase 前面,而且class SmartPointer中的定义也没有看到用: 继承之类的操作,mPointer怎么就凭空能调用 mPointer->incRefCount()等这些方法?


文章接下来是这样用的,下面我理解,上面的定义部分我不能理解:

/* 
* file name : sptestcase3.cpp
* desp : 智能指针测试代码 case3 测试智能指针的引用计数功能
*/

#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 testcase3(void)
{
SomeClass *pSomeClass = new SomeClass(); //1
SmartPointer<SomeClass> spOuter = pSomeClass;
std::cout << "SomeClass Ref Count (" << pSomeClass->getRefCount() << ") outer 1."<< std::endl;
{ // inner 语句块
SmartPointer<SomeClass> spInner = spOuter;
std::cout << "SomeClass Ref Count (" << pSomeClass->getRefCount() << ") inner."<< std::endl;
}
std::cout << "SomeClass Ref Count (" << pSomeClass->getRefCount() << ") outer 2."<< std::endl;
// delete pSomeClass ; 不需要也不能执行delete操作!

std::cout << "new another SomeClass class for spOuter."<< std::endl;
SmartPointer<SomeClass> spOuter2 = new SomeClass();
spOuter = spOuter2;// 1处new出来的SomeClass将会被自动释放
}

int main(void)
{
testcase3();
return 0;
}



原文:https://www.shiyanlou.com/courses/745/labs/2505/document
...全文
评论 8
收藏 已收藏
分享
返回顶部
bandaoyu
C++ 语言 65,214 成员 250,514 内容