1.
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 []>());
// 完全可以避免写手动的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;
});
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 等容器中。