智能指针:从std::auto_ptr到std::unique_ptr
2012-12-15 21:38
381 查看
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::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
- C++11引入智能指针std::unique_ptr
- std::auto_ptr boost::shared_ptr智能指针的应用
- c++智能指针:std::auto_ptr
- C++ 智能指针学习 auto_ptr, unique_ptr 。。。
- 智能指针 std::auto_ptr 和 shared_ptr
- auto_ptr, unique_ptr, shared_ptr and weak_ptr智能指针讲解
- 正确使用 std::auto_ptr 智能指针
- 智能指针 std::auto_ptr 和 shared_ptr
- C++11智能指针之std::unique_ptr
- [置顶] STL中的智能指针(Smart Pointer)及其源码剖析: std::unique_ptr
- 智能指针–std::auto_ptr
- C++中的智能指针——auto_ptr, unique_ptr, shared_ptr和weak_ptr
- 浅谈智能指针auto_ptr/shared_ptr/unique_ptr
- 剖析C++标准库智能指针(std::auto_ptr) 以及智能指针的原理
- 智能指针 std::auto_ptr 和 shared_ptr
- 实战c++中的智能指针unique_ptr系列-- 使用std::unique_ptr代替new operator(错误:‘unique_ptr’ is not a member of ‘std’)
- [置顶] STL中的智能指针(Smart Pointer)及其源码剖析: std::auto_ptr
- 实战c++中的智能指针unique_ptr系列-- 使用std::unique_ptr代替new operator(错误:‘unique_ptr’ is not a member of ‘std’)
- stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结