5种创建指向数组的智能指针shared_ptr/unique_ptr的方法

Posted sean-zhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了5种创建指向数组的智能指针shared_ptr/unique_ptr的方法相关的知识,希望对你有一定的参考价值。

//OK, pointer to int 999
std::shared_ptr<int> sp(new int(999)); 


template< typename T >
struct array_deleter

  void operator ()( T const * p)
   
    delete[] p; 
  
;

// pointer to int array, 
// (1) provide array deleter
std::shared_ptr<int> sp(new int[10], array_deleter<int>()); 

// (2) or lambda expression 
std::shared_ptr<int> sp(new int[10], [](int *p)  delete[] p; );

// (3) or use default_delete
std::shared_ptr<int> sp(new int[10], std::default_delete<int[]>());

// (4) or we can use unique_ptr
std::unique_ptr<int[]> up(new int[10]); // this will correctly call delete[]

以上是关于5种创建指向数组的智能指针shared_ptr/unique_ptr的方法的主要内容,如果未能解决你的问题,请参考以下文章

5种创建指向数组的智能指针shared_ptr/unique_ptr的方法

指向指针数组和指针数组的指针之间的区别[重复]

第61课 智能指针类模板

C/C++知识要点5——智能指针原理及自己定义实现

c++如何用指针指向二维数组

如何创建指针数组?