一步一步 实现智能指针(三)
来源:互联网 发布:javascript 表格并排放 编辑:程序博客网 时间:2024/05/17 22:41
//再依据 封装等。。将他代码,整理优化
#include <iostream>
using namespace::std;
/**
* 计数器类。
* 对一个地址的引用计数
* 需要单独封装成一个类,这样才能把它作为 MySmartPoint的一个指针成员,才能保证,所有 同一个 对象T 用同一个计数器 具体演变过程看那前面的文章
*/
class Counter
{
private:
int count;
template <class T> friend class MySmartPoint;
};
/**
* 智能指针类,对指针进行管理
* 保证了 new delete 对称
* 考虑了 赋值,拷贝,
*/
template <class T>
class MySmartPoint
{
private:
T *ptr;
Counter *countPtr; //记录ptr 个数
public:
// MySmartPoint(){};//这个应收是没有意义的 构造方法
MySmartPoint(T *p)
{
countPtr = new Counter();
countPtr -> count =1;
cout<< "count =" << countPtr -> count <<endl;
this->ptr = p;
};
MySmartPoint(const MySmartPoint & sp)
{
sp.countPtr->count ++;
countPtr = sp.countPtr;
ptr = sp.ptr;
cout<< "count =" << countPtr -> count <<endl;
std::cout << "const 拷贝构造" << std::endl;
}
MySmartPoint(MySmartPoint &sp)
{
sp.countPtr->count ++;
countPtr = sp.countPtr;
ptr = sp.ptr;
cout<< "count =" << sp.countPtr -> count <<endl;
std::cout << " 拷贝构造" << std::endl;
};
~MySmartPoint()
{
countPtr -> count --;
cout<<"析构 count= "<<countPtr -> count <<endl;
if (0 == countPtr -> count)
{
delete this->ptr;
cout<< "delete point is "<<this->ptr<<endl;
}
}
MySmartPoint& operator=(const MySmartPoint &p)
{
if (this == &p)
{
return *this;
}
p.countPtr->count ++;
countPtr->count --;
if (countPtr->count == 0)
{
delete this->ptr;
cout<< "delete point is "<<this->ptr<<endl;
}
countPtr = p.countPtr;
ptr = p.ptr;
std::cout << " operator=" << std::endl;
return *this;
}
T* operator->()
{
return ptr;
}
const T* operator->()const
{
return ptr;
}
T &operator*()
{
return *ptr;
}
const T &operator*()const
{
return *ptr;
}
};
class Point
{
private:
int x;
int y;
public:
Point(int xVal,int yVal):x(xVal),y(yVal)
{
std::cout<<"creat point adress is "<<this <<std::endl;
}
~Point()
{
std::cout<<"relase point adress is "<<this <<std::endl;
}
int getX()
{
return x;
};
int getY()
{
return y;
}
};
int main()
{
Point *p = new Point(3,4);
MySmartPoint<Point> sp = MySmartPoint<Point>(p);
MySmartPoint<Point> sp1 = MySmartPoint<Point>(sp);
MySmartPoint<Point> sp2 = sp;
MySmartPoint<Point> sp3 = MySmartPoint<Point>(new Point(1,2));
sp3 = sp;
cout<< sp3->getX()<<endl;
cout<< "over"<<endl;
}
- 一步一步 实现智能指针(三)
- 一步一步 实现智能指针(一)
- 一步一步 实现智能指针(二)
- C++智能指针(二)模拟实现三种智能指针
- C++智能指针(二):模拟实现三种智能指针
- C++ STL智能指针(三)
- C++智能指针(三)总结
- C++回顾(三)智能指针
- 智能指针(三)之scoped_ptr
- 三、智能指针
- 线性表(智能指针实现)
- C++ primer智能指针(HasPtr)实现
- C++ primer智能指针(HasPtr)实现
- C++ primer智能指针(HasPtr)实现
- C++ 智能指针实现
- 智能指针实现方式
- 手动实现智能指针
- 智能指针实现
- bootstrap 学习笔记 - 5 (Glyphicons字体 + 下拉菜单 + 按钮组+ 按钮下拉菜单)
- Java语言描述:回溯法之批处理作业调度
- 推荐学习网站
- 黑马程序员_java语言_IO其他流
- 多线程与并发库高级应用
- 一步一步 实现智能指针(三)
- LightOJ1007---Mathematically Hard (欧拉函数)
- OpenCV学习笔记09--通过cvPtr2D或指针算法绘制图形
- 青春
- 泰国清迈8天自由行小结
- DLL的进入退出——由DLL_PROCESS_ATTACH而联系搜索起来。
- [C#] 汉字转拼音,支持多音字
- 排列组合算法之三: 递归法
- gdb调试dce