1

I am curious to know, how shared_ptr class decides whether it has to call delete or delete[] for the below statements?

a. boost::shared_ptr <char> ptr(new char);

b. boost::shared_ptr <char []> ptr(new char[100]);

Vishnu Kanwar
  • 761
  • 5
  • 22
  • 1
    I would imagine you tell it which to call with the parameter, it being either `` or ``. – Galik Feb 19 '20 at 05:32
  • 2
    Boost have many types of "smart" pointers, but none called `boost::smart_ptr`. – Some programmer dude Feb 19 '20 at 05:32
  • 3
    As for your question, please do some research about [*specialization*](https://www.geeksforgeeks.org/template-specialization-c/). – Some programmer dude Feb 19 '20 at 05:33
  • 1
    The `` version is specialized to always use `delete` by default. The `` version is specialized to always use `delete[]` by default. There is no decision to make. The template parameter determines which specialization is used. – Remy Lebeau Feb 19 '20 at 05:58

1 Answers1

3

It is done via template specialization. Here is the simple demonstration.

#include <iostream>
#include <type_traits>

template<typename T>
struct foo
{
    foo( T* d ) : m_data{ d } {  }
    ~foo() {
        if ( m_data )
        std::cout << "delete called." << std::endl;
    }

private:
    T* m_data {};
};

template<typename T>
struct foo<T[]>
{
    foo( T* d ) : m_data { d } { }
    ~foo() {
        if ( m_data )
            delete[] m_data;
        std::cout << "delete[] called." << std::endl;
    }
private:
    T* m_data {};
};

int main()
{
    foo<char> inst_1 { new char };
    foo<char []> inst_2 { new char[ 100 ] { 'a' } };
}

online example

For T[] types, struct foo<T[]> instantiated, so compile-time polymorphism is done via template specialization and smart_ptr handles deallocation of both array and normal types with the help of this feature.

calynr
  • 1,264
  • 1
  • 11
  • 23