C++ 的智能指针
来源:互联网 发布:施工动画软件 编辑:程序博客网 时间:2024/06/04 23:39
为什么需要智能指针?
内存泄漏:动态申请空间,用完后忘记归还; C++语言中没有垃圾回收的机制;指针无法控制所指堆空间的生命周期
我们需要什么
需要一个特殊的指针,指针生命周期结束时主动释放堆空间,一片堆空间最多只能一个指针标识,杜绝指针运算和指针比较
解决方案
重载指针特征操作符(-> 和 * );只能通过类的成员函数重载;重载函数不能使用参数;只能定义一个重载函数
#include <iostream>#include <string>using namespace std;class Test{ int i;public: Test(int i) { cout << "Test(int i)" << endl; this->i = i; } int value() { return i; } ~Test() { cout << "~Test()" << endl; }};class Pointer{ Test* mp;public: Pointer(Test* p = NULL) { mp = p; } Pointer(const Pointer& obj) { mp = obj.mp; const_cast<Pointer&>(obj).mp = NULL; } Pointer& operator = (const Pointer& obj) { if( this != &obj ) { delete mp; mp = obj.mp; const_cast<Pointer&>(obj).mp = NULL; } return *this; } Test* operator -> () { return mp; } Test& operator * () { return *mp; } bool isNull() { return (mp == NULL); } ~Pointer() { delete mp; }};int main(){ Pointer p1 = new Test(0); cout << p1->value() << endl; Pointer p2 = p1; cout << p1.isNull() << endl; cout << p2->value() << endl; return 0;}
智能指针只能用来指向堆空间中的对象或者变量
小结:指针特征操作符( -> 和 * )可以被重载
重载指针特征符能够使用对象代替指针
智能指针只能用于指向堆空间中的内存
智能指针的意义在于最大程度的避免内存问题
0 0
- 【C++】智能指针的实现
- [c++]智能指针的实现
- 【C++】智能指针的一个典型应用
- 【C++】智能指针auto_ptr的简单实现
- C++(智能指针的设计与实现)
- C++:auto_ptr智能指针的用法
- (C++)智能指针的小“自传”
- c++:智能指针
- C++:智能指针
- 【C++】智能指针
- 【C++】智能指针
- C++PJ智能指针
- 【c++】智能指针
- 【C++】智能指针auto_ptr
- C++,智能指针
- C++,boost智能指针
- 智能指针模拟C
- [C++]智能指针
- Linux中的LVM详解
- 并发系统
- 两个指针变量的减法
- c语言printf和指针初识
- OKHTTP之缓存配置详解
- C++ 的智能指针
- mysql忘记密码后的解决方法
- armlinuxgcc 安装经验
- 抽象工厂
- 20161129
- git命令大全
- 算法设计与优化编程 第十讲 Subway
- UVALive 7500 Boxes and Balls (二分)
- Java8之Lambda表达式