有的时候需要由local函数在heap中alloc 一个数组空间并返回给外部使用。例如在windows编程中常常需要转换编码,
转换编码返回值常常是alloc 在heap中如果例如返回一个char *. 如果外部在使用完以后不做删除操作就容易造成内存泄漏。
本质上char* 在heap中是一个char[] 。可以将返回值存在智能指针中,来自动销毁(shared_ptr, unique_ptr)
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[]>());
unique_ptr跟shared_ptr不一样,它直接支持持有数组对象
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],