智能指针:从std::auto_ptr到std::unique_ptr
来源:互联网 发布:公司网络越狱 编辑:程序博客网 时间:2024/06/05 18:40
std::auto_ptr封装动态申请对象内存返回的指针,并且其行为也和普通指针一样。最重要的一点,程序员不必记得去释放之前申请的内存,当std::auto_ptr销毁时,其封装的指针所指向的内存也会自动销毁。当需要处理异常时,这尤其重要,RAII技术保证异常发生后,在栈上保存的对象依次销毁释放,直至异常被捕获。
当动态申请对象数组时,std::auto_ptr就不在适用了。这是因为std::auto_ptr销毁函数(析构函数)的默认实现是调用delete操作符销毁所封装对象的内存空间(包括调用对象的析构函数),而动态申请的数组需要适用delete[]释放空间(包括调用数组汇总各个对象的析构函数)。如果delete和new操作符不能匹配使用,其结果是不确定的。当然如果申请的数组不是用户定义的数据类型(指int, char等所支持的基本类型),则不存在问题(malloc都是和free匹配使用)。
boost::scoped_array/boost::shared_array是适用于数组的智能指针,不存在上述问题[1]。
std::auto_ptr在最新的c++11标准草案中被std::unique_ptr取代[2,3]。std::unique_ptr支持封装数组动态申请
[1] http://en.highscore.de/cpp/boost/
[2] http://en.wikipedia.org/wiki/C%2B%2B11
[3] "Working Draft, Standard for Programming Language C++"
- 智能指针:从std::auto_ptr到std::unique_ptr
- 智能指针std::auto_ptr
- C++11 智能指针std::shared_ptr/std::unique_ptr/std::weak_ptr
- [4]智能指针std::auto_ptr
- c++智能指针:std::auto_ptr
- 智能指针–std::auto_ptr
- 关于std:auto_ptr std:shared_ptr std:unique_ptr
- C++11引入智能指针std::unique_ptr
- C++11智能指针之std::unique_ptr
- C++标准库智能指针(std::auto_ptr)
- C++标准库智能指针(std::auto_ptr)
- 智能指针 std::auto_ptr 和 shared_ptr
- 智能指针 std::auto_ptr 和 shared_ptr
- 智能指针 std::auto_ptr 和 shared_ptr
- C++标准库智能指针(std::auto_ptr)
- 剖析C++标准库智能指针(std::auto_ptr)
- 剖析C++标准库智能指针(std::auto_ptr)
- 剖析C++标准库智能指针(std::auto_ptr)
- 开始学淘宝API
- 黑马程序员-SQL Server中一些有用的日期SQL语句
- COM, COM+ and .NET 的区别
- 黑马程序员_java初级基础知识汇总(常量和变量、语句、函数、数组)
- ios开发学习--列表(Table)效果源码分享--系列教程
- 智能指针:从std::auto_ptr到std::unique_ptr
- 第一个app应用TaxiDaren应用终于发布了!
- performSelector使用
- 关于SQL Server 2008 数据库 不允许保存修改的解决办法
- rails server 错误
- Qt4精彩实例分析笔记--标准对话框的使用
- C# 獲取照片拍攝時間
- 统计字母
- How to store CGPoint or CGRect in NSArray?