c++智能指针练习
来源:互联网 发布:沈阳思迅软件 编辑:程序博客网 时间:2024/06/05 17:22
实例如下:
写的不太标准,主要参考c++ primer中的讲解
#include <iostream>using namespace std;class counter{int m_use; template <class T> friend class smartpointer; counter(int use):m_use(use){} counter(){ m_use = 0;}};template <class T>class smartpointer{public:smartpointer(T *ptr):m_pt(ptr),m_cnt(new counter(1)){cout<<"smartpointer::smartpointer() invoked " << m_cnt->m_use++ <<endl;}smartpointer(const smartpointer<T>& rhs){ m_pt = rhs.m_pt;m_cnt = rhs.m_cnt; ++(m_cnt->m_use);cout<<"smartpointer::smartpointer(const smartpointer&) invoked " << m_cnt->m_use++ <<endl;}~smartpointer(){cout<<"SmartPointer::~SmartPointer() invoded" << m_cnt->m_use <<endl;if(--(m_cnt->m_use) == 0){delete m_pt;delete m_cnt;}}smartpointer& operator=(const smartpointer& rhs){if(rhs == *this)return *this;m_pt = rhs.m_pt;m_cnt = rhs.m_cnt;++(m_cnt->m_use);cout<<"SmartPointer::operator=SmartPointer() invoded" << m_cnt->m_use <<endl;return *this;}private:T *m_pt;counter *m_cnt;};class test{private:int t;int *value;public:test(int v):t(v), value(& v){cout << t <<endl;}~test(){delete value;cout << "test::~test() invoked" <<endl;}};int main(int argc, char *argv[]){test *t = new test(10);smartpointer<test> pp(t);smartpointer<test> pp2(pp);smartpointer<test> pp3 = pp2; return 0;}
写的不太标准,主要参考c++ primer中的讲解
0 0
- c++智能指针练习
- c++:智能指针
- C++:智能指针
- 【C++】智能指针
- 【C++】智能指针
- C++PJ智能指针
- 【c++】智能指针
- 【C++】智能指针auto_ptr
- C++,智能指针
- C++,boost智能指针
- 智能指针模拟C
- [C++]智能指针
- 【C++】 浅析智能指针
- C++_智能指针
- C++:初识智能指针
- C++::智能指针
- 【C++】智能指针
- c智能指针:unique_ptr
- c++ stl容器
- 彻底解决_OBJC_CLASS_$_某文件名", referenced from:问题(转)
- Makefile例子
- Mac 10.10.2编译Hadoop-2.6.0-src
- 求质数
- c++智能指针练习
- 第一章13和14题
- 第5周项目1-体验常成员函数
- Google推荐的图片加载库Glide介绍
- 缓存、缓存算法和缓存框架简介
- soap异常处理
- 蓝桥杯---平面四点最小距离
- 一、Android 图片加载框架 Fresco 入门
- 虚方法与抽象方法有什么区别