37-智能指针分析
来源:互联网 发布:青年网络公开课主持人 编辑:程序博客网 时间:2024/06/04 17:42
1、
#include <iostream>#include <string>using namespace std;class Test{ int i;public: Test(int i) { this->i = i; } int value() { return i; } ~Test() { }};int main(){ for(int i=0; i<5; i++) { Test* p = new Test(i); cout << p->value() << endl; } return 0;}01234但是没有释放指针对应的内存,造成内存泄露
2、需求
智能指针是一个类实现指针的功能
3、
#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;//将原来的指针赋值为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;}Test(int i)010~Test()
4、
5、小结
阅读全文
0 0
- 37-智能指针分析
- webkit 智能指针分析
- 智能指针小分析
- 批注:智能指针分析
- 智能指针分析
- Android6.0 智能指针分析
- c++:简单分析智能指针
- STL auto_ptr智能指针简单分析
- STL+auto_ptr智能指针简单分析
- STL+auto_ptr智能指针简单分析
- Android智能指针分析(sp、wp)
- 智能指针的分析与实现
- Android智能指针分析(sp、wp)
- Android 5.0源码分析---智能指针
- 基础备忘:智能指针小分析
- Android智能指针分析(sp、wp)
- Android智能指针分析(sp、wp)
- boost 智能指针 shared_ptr 原理分析
- 机器人领域的期刊和会议
- CentOs 7怎么联网 怎么配置静态IP
- 扫雷
- CodeForces
- 欢迎使用CSDN-markdown编辑器
- 37-智能指针分析
- redis常用命令
- Spring中的@Async注解 异步任务处理
- CentOS 7.0系统安装配置图解教程
- HIVE和HBASE区别
- 并发系统
- MySql 7大join连接关系
- 使用Spring Social开发第三方登陆
- content-length bytes were read and there was no trailing null byte