c++11 智能指针碰到的问题总结
2014-04-14 13:45
190 查看
1.
//C++11的<memory>中有一整套智能指针,
//完全可以避免写手动的delete代码,
//但是它默认使用delete删除对象,
//如果是数组对象,需要指定自定义的删除方法,支持delete[]
std::shared_ptr<int> p(new int[10],
[](int* p){
delete[] p;
});
//或者使用helper
std::shared_ptr<int> p(new int[10],std::default_delete<int[]>());
std::unique_ptr<int[]> p(new int[10]);//ok
std::shared_ptr<int[]> p(new int[10]);//error, does not compile
std::unique_ptr<int, void(*)(int*)> p(new int[10],
[](int* p){
delete[] p;
});
2.
std::auto_ptr 可用来管理单个对象的对内存,但是,请注意如下几点:
(1) 尽量不要使用“operator=”。如果使用了,请不要再使用先前对象。
(2) 记住 release() 函数不会释放对象,仅仅归还所有权。
(3) std::auto_ptr 最好不要当成参数传递(读者可以自行写代码确定为什么不能)。
(4) 由于 std::auto_ptr 的“operator=”问题,有其管理的对象不能放入 std::vector 等容器中。
C++11智能指针处理Array对象
//C++11的<memory>中有一整套智能指针,//完全可以避免写手动的delete代码,
//但是它默认使用delete删除对象,
//如果是数组对象,需要指定自定义的删除方法,支持delete[]
std::shared_ptr<int> p(new int[10],
[](int* p){
delete[] p;
});
//或者使用helper
std::shared_ptr<int> p(new int[10],std::default_delete<int[]>());
std::unique_ptr<int[]> p(new int[10]);//ok
std::shared_ptr<int[]> p(new int[10]);//error, does not compile
std::unique_ptr<int, void(*)(int*)> p(new int[10],
[](int* p){
delete[] p;
});
2.
std::auto_ptr 可用来管理单个对象的对内存,但是,请注意如下几点:
(1) 尽量不要使用“operator=”。如果使用了,请不要再使用先前对象。
(2) 记住 release() 函数不会释放对象,仅仅归还所有权。
(3) std::auto_ptr 最好不要当成参数传递(读者可以自行写代码确定为什么不能)。
(4) 由于 std::auto_ptr 的“operator=”问题,有其管理的对象不能放入 std::vector 等容器中。
相关文章推荐
- C++技术问题总结-第9篇 智能指针
- C++11中的智能指针
- JfreeChart使用经验总结(分析了使用中碰到的一些常见问题)
- WebRTC编译过程中碰到的问题总结
- C++11智能指针之unique_ptr
- C++11智能指针
- C/C++"野指针"问题总结
- (转载)【C++11新特性】 C++11智能指针之weak_ptr
- 总结ldap碰到的问题
- 使用 C++11 智能指针时要避开的 10 大错误
- operator->重载问题总结 让一个对象表现的像一个指针
- 给客户搭建RAC-DG时碰到的一些问题总结
- C++11智能指针的常见误区 Top10
- C++11-智能指针和空指针
- vs2008 使用母版页时碰到[js的智能提示]和[相对路径] 的问题。
- C++11-智能指针-shared_ptr
- 智能指针学习总结
- ubantu下安装mysql教程以及碰到的问题总结
- C++11 FAQ中文版:共享资源的智能指针——shared_ptr
- C++11智能指针的选择使用