C++ 智能指针的使用
来源:互联网 发布:sql 删除数据库语句 编辑:程序博客网 时间:2024/05/17 18:02
// auto_ptr.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"// 计数类class smart_count{public: smart_count(int c):m_count(c){} ~smart_count(){} int addRef() { return m_count++; } int releaseRef() { if (m_count--) { return m_count; } else return 0; } int getCount() { return m_count; }private: int m_count;};template <class T>class auto_ptr{public: //! 防止隐式转换 explicit auto_ptr(T *p):ptr(p),m_csmart_count(new smart_count(1)){} auto_ptr():ptr(NULL),m_csmart_count(NULL){} //! 拷贝构造函数 auto_ptr(const auto_ptr<T>& t) { ptr = t.ptr; m_csmart_count = t.m_csmart_count; if (m_csmart_count) { m_csmart_count->addRef(); } } //! 重载赋值运算符 auto_ptr<T>& operator=(const auto_ptr<T>& t) { if (t.m_csmart_count) { t.m_csmart_count->addRef(); } ptr = t.ptr; m_csmart_count = t.m_csmart_count; return *this; } //! 析构函数 ~auto_ptr() { if (ptr && m_csmart_count->releaseRef() <= 0) { delete ptr; delete m_csmart_count; ptr = NULL; } } void prtRef() { printf("%d\n", m_csmart_count->getCount()); }protected:private: smart_count *m_csmart_count; T *ptr; };int _tmain(int argc, _TCHAR* argv[]){ char *p = "123"; auto_ptr<char> au_p(p); auto_ptr<char> au_p1=au_p; au_p1.prtRef(); au_p1.~auto_ptr(); au_p.prtRef(); getchar();return 0;}
自己简单实现的一个智能指针类,暂时还没有重载 * 和 ->等操作符。
- 智能指针的使用
- 智能指针的使用
- 智能指针的使用
- 智能指针的使用
- C++:指向数组的智能指针scoped_array组件的使用
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- (C++)智能指针的模拟实现及使用
- 【C++】智能指针的实现
- [c++]智能指针的实现
- 智能指针 _com_ptr_t的使用
- 使用智能指针的危险
- C++ 智能指针的使用
- 智能指针auto_ptr的使用
- ADO智能指针的使用
- C++ 智能指针的使用
- c++智能指针的使用
- C++智能指针的使用
- The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files
- XML-RPC, SOAP 的区别
- C程序设计语言中文版
- 对于堆排序的一些想法
- 如何重新设置bimpat的大小?
- C++ 智能指针的使用
- Linux运维趋势:阿里运维监控那些事儿
- javascript实现hashmap
- 导入工程的“The import android cannot be resolved”错误解决方法
- Mysql并发控制
- 人人网移动开发架构及相关服务器架构
- cookie 和session 的区别详解
- Nginx 支持pathinfo模式
- 基于云技术的商务智能