C++智能指针
来源:互联网 发布:淘宝乐高霍比特人玩具 编辑:程序博客网 时间:2024/06/05 22:58
C++编程中,使用智能指针可以有效避免内存泄漏。现有的智能指针比较多,例如std::auto_ptr。参考资料[7]指出,auto_ptr是一个类(由此可以推断,其它的智能指针也是如此)。
下面将对C++中常用的智能指针做一个简单的总结。
1 std::auto_ptr
参考资料[4]P63指出,auto_ptr是个”类指针(pointer-like)对象“,也就是所谓的”智能指针“,其析构函数自动对其所指对象调用delete。关于auto_ptr的详细说明(包括具体实现),见参考资料[7]。
1.1 特性
参考资料[4]P63P68指出,当复制一个auto_ptr对象时,资源的拥有权会从旧auto_ptr转移到新auto_ptr对象上,旧auto_ptr变成null。
1.2 使用示例(ubuntu 14.04.1)
#include <memory>// auto_ptr所需头文件int main(int argc, char*argv[]){std::auto_ptr<int> pInt(new int( 1 ) ); // auto_ptr使用实例return 0;}
2 std::tr1::shared_ptr
2.1 TR1
参考资料[4]P9说明,TR1(Technical Report 1)是一份规范,描述加入C++标准程序的诸多新机制,例如shared_ptr。参考资料[1]对此有更为详细的说明。
2.2 特性
参考资料[4]P64指出,与auto_ptr不同的是,复制shared_ptr对象并不会导致旧shared_ptr对象变为null,因为shared_ptr是“引用计数型智能指针”;另外,参考资料[4]P68说明,由于shared_ptr可以指定“删除器”,因此可以用于实现对互斥锁进行加锁/解锁管理。
2.3 使用示例(ubuntu 14.04.1)
#include <tr1/memory>// 要使用shared_ptr,需要这个头文件int main(int argc, char*argv[]){std::tr1::shared_ptr<int> pInt(new int(1)); // shared_ptr使用实例return 0;}
参考资料
[1]C++ TR1 和 C++0x
[2]linux下如何使用C++ tr1
[3]c++标准扩展TR1
[4]Effective C++,中文版(第三版)
[5]C++中智能指针的设计和使用
[6]智能指针_百度百科
[7]auto_ptr_百度百科
- c++:智能指针
- C++:智能指针
- 【C++】智能指针
- 【C++】智能指针
- C++PJ智能指针
- 【c++】智能指针
- 【C++】智能指针auto_ptr
- C++,智能指针
- C++,boost智能指针
- 智能指针模拟C
- [C++]智能指针
- 【C++】 浅析智能指针
- C++_智能指针
- C++:初识智能指针
- C++::智能指针
- 【C++】智能指针
- c智能指针:unique_ptr
- 【C++】智能指针
- Kali Linux 建立无线热点 · RTL8188CUS
- 黑马程序员——Map、HashMap、TreeMap
- 基于注解,HandlerInterceptorAdapter 拦截器
- 【.Net码农】.NET中执行js脚本的方法
- WSDL详解
- C++智能指针
- error 0152: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.
- 算法导论中的数论算法(一)
- 卡片游戏
- TestNG 安装及使用入门(webDriver+java环境)
- leetcode 76: Minimum Window Substring
- 大数据爬虫实习面试题
- 欢迎使用CSDN-markdown编辑器
- Android:剖析源码,随心所欲控制Toast显示