DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
基础知识:
智能指针的设计与实现:
1.智能指针类将一个计数器与类指向的对象相关联,引用计数跟踪该类有多少个对象共享同一指针。
2.每次创建类的新对象时,初始化指针并将引用计数置为1;
3/当对象作为另一对象的副本而创建时,拷贝构造函数拷贝指针并增加与之相应的引用计数;
4.对一个对象进行赋值时,赋值操作符减少左操作数所指对象的引用计数(如果引用计数为减至0,则删除对象),并增加右操作数所指对象的引用计数;
5.调用析构函数时,构造函数减少引用计数(如果引用计数减至0,则删除基础对象)。
6.所有的智能指针都会重载 -> 和 * 操作符。智能指针还有许多其他功能,比较有用的是自动销毁。
 
 
 
#include <iostream>
#include <memory>
 
using namespace std;
 
template <typename T>
class smartpointer{
public:
//构造函数
smartpointer(T* ptr = NULL) :_ptr(ptr)
{
if (_ptr)//如果实例化了,就建立计数器
{
_count = new size_t(1);
}
else{
_count = new size_t(0);
}
}
 
//拷贝构造函数(相同的话就不拷贝)
smartpointer(const smartpointer& smp)
{
if (this == &smp)
return;
else{
this->_ptr = smp._ptr;
this->_count = smp._count;
(*this->_count)++;
}
}
 
//赋值函数(左值减少,右值增加)  //特别说明:不是构造函数
smartpointer& operator = (const smartpointer& smp)
{
if (this->_ptr == smp._ptr)
{
return *this;
}
 
if (this->_ptr)
{
(*this->_count)--;
if ((*this->_count) == 0)
{
delete this->_ptr;
delete this->_count;
}
}
 
this->_ptr = smp._ptr;
this->_count = smp._count;
(*this->_count)++;
return *this;
}
 
//重载->和*
T& operator -> ()
{
assert(this->_ptr == NULL);
return (*this->_ptr);
}
 
T* operator * ()
{
assert(this->_ptr == NULL);
return this->_ptr;
}
 
size_t use_count()
{
return *this->_count;
}
 
//析构函数
~smartpointer()
{
if (*this->_count == 0)
{
delete this->_ptr;
delete this->_count;
cout << "释放" << endl;
}
else{
(*this->_count)--;
if (*this->_count == 0)
{
delete this->_ptr;
delete this->_count;
cout << "释放" << endl;
}
}
}
private:
T* _ptr;
size_t* _count;
};
 
int main() {
{
//只初始化了两次
smartpointer<int> sp(new int(10));
smartpointer<int> sp2(sp);
smartpointer<int> sp3(new int(20));
sp2 = sp3;
std::cout << sp.use_count() << std::endl;
std::cout << sp3.use_count() << std::endl;
 
//SmartPointer<int> sp(NULL);
//std::cout << sp.use_count() << std::endl;
}
 
system("pause");
return 0;
}
posted on   DoubleLi  阅读(152)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2023-01-03 error C2447: “{”: 缺少函数标题(是否是老式的形式表?)
2019-01-03 code block自动生成makefile
2019-01-03 centos7 安装 codeblock(rpm)
2018-01-03 一个程序员6年的浏览器收藏夹
2015-01-03 nginx相关参考博客
2015-01-03 Nginx学习之三-ngx_http_request_t结构体
2015-01-03 Nginx学习之二-配置项解析及编程实现
点击右上角即可分享
微信分享提示