C/C++:智能指针原理(运算符重载)、使用auto_ptr<A>
2014-08-04 15:16
531 查看
智能指针:能够自动释放从堆中申请的资源
原理如下:(实现运算符“*”以及‘->’的重载)
1、定义一个类用于狗仔存放数据的对象
2、定义智能指针类
测试:
注意:智能指针类可以使用auto_ptr<classname>obj(newclassname)模板代替
原理如下:(实现运算符“*”以及‘->’的重载)
1、定义一个类用于狗仔存放数据的对象
classA { public: A(){ cout<<"构造函数"<<endl; } ~A(){ cout<<"析构函数"<<endl; } stringm_str;//m_str用于存放字符串 };
2、定义智能指针类
classPta{ public: Pta(A*pa):m_pa(pa){}//在初始化列表中分配资源,初始化指针A*m_pa ~Pta() { deletem_pa;//在析构函数中释放资源 } A*operator->(void)const//运算符->重载 { returnm_pa;}//返回指针 A&operator*(void)const { return*m_pa;//返回引用 } private: A*m_pa; };
测试:
intmain() { //A*p=newA; //p->m_str="hello"; Ptapa(newA); pa->m_str="hello"; cout<<(*pa).m_str<<endl;
auto_ptr<A>pa(newA);
pa->m_str="hello";
cout<<(*pa).m_str<<endl;
}
注意:智能指针类可以使用auto_ptr<classname>obj(newclassname)模板代替
相关文章推荐
- C++智能指针auto_ptr的原理及使用
- 一个类似auto_ptr<>用于动态分配数组的智能指针
- [置顶] 从零开始学C++之boost库(一):详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- C++智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> )
- [C/C++标准库]_[初级]_[使用auto_ptr智能指针]
- [置顶] 从零开始学C++之boost库(一):详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- [置顶] 从零开始学C++之对象语义与值语义、资源管理(RAII、资源所有权)、模拟实现auto_ptr<class>、实现Ptr_vector .
- 实战c++中的vector系列--使用sort算法对vector<unique_ptr<string>>进行排序(sort函数出错“应输入 2 个参数,却提供了 3 个)
- C++智能指针,指针容器原理及简单实现(auto_ptr,scoped_ptr,ptr_vector).
- [C/C++标准库]_[初级]_[使用auto_ptr智能指针]
- c++ standard library 学习笔记-auto_ptr<T> 注意事项
- <C/C++> FILE指针的使用
- 【VS开发】【C++开发】正确使用auto_ptr智能指针
- 智能指针里弱引用应该如何实现?(WeakReference/WeakPtr<T>)
- 从零开始学C++之boost库(一):详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- C++智能指针,指针容器原理及简单实现(auto_ptr,scoped_ptr,ptr_vector).
- C++中的auto_ptr智能指针的作用及使用方法详解
- [ADO&VC一]使用ADO智能指针_ConnectionPtr,_CommandPtr及_RecordsetPtr
- 剖析C++标准库智能指针(std::auto_ptr) 以及智能指针的原理
- 智能指针auto_prt的使用(c++学习笔记)