May 28, 2018

[C++][C++17] shared_ptr now taking array type

boost::shared_array (deprecated) due to now(C++17) shared_ptr takes array type.

cppref:
std::shared_ptr::operator[]

Prior C++17, we need to provide ourselves a array deleter in order to allow shared_ptr taking array type.

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

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

// or
std::shared_ptr<int> sp(new int[10], std::default_delete<int>());
//or
std::shared_ptr<int> sp(new int[10], [](int *p) { delete[] p; });
Reference:
https://stackoverflow.com/a/13062069

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.