C++11中使用std::share_ptr管理指向普通类型指针的动态数组时一点注意

参考文章:

shared_ptr to an array : should it be used?

在创建指向普通类型的动态数组时,需指定对应的删除函数

如:

template< typename T >
struct array_deleter
{
  void operator ()( T const * p)
  { 
    delete[] p; 
  }
};

std::shared_ptr<int> sp(new int[10], array_deleter<int>());

或者

//使用Std的删除函数
std::shared_ptr<int> sp(new int[10], std::default_delete<int[]>());

//使用lambda表达式
std::shared_ptr<int> sp(new int[10], [](int *p) { delete[] p; });
为什么这么做呢,因为如果不指定的话,默认调用的析构方法是 delete, 而我们析构数组时,需要调用 delete[] ,在析构数组的地方使用delete 会引起内存泄漏。

猜你喜欢

转载自blog.csdn.net/humadivinity/article/details/80484850