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]);
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]);
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' } };
}
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.