Search code examples
c++shared-ptrsmart-pointers

Stuck in understanding following initialization way of shared_ptr


A class is defined as follows:

#include<memory>
using namespace std;
class A
{
public:
    A(int n) : data{new int[n],default_delete<int[]>()}{}
    shared_ptr<int> data;
};

So how to understand data{new int[n],default_delete<int[]>()}. The initialization way data{} is strange to me since I am not familiar with C++11. To my understanding, whether this way means letting data pointing to consecutive heap memory first then defining the way freeing this memory as delete int[] instead of delete int?


Solution

  • You just use one the std::shared_ptr's constructors (see here):

    template< class Y, class Deleter > 
    shared_ptr( Y* ptr, Deleter d );
    

    Where default_delete has specialization for array (see here).