This is example of smart pointer with type erased deleter and local buffer optimization enabled. It is from the book https://books.google.am/books/about/Hands_On_Design_Patterns_with_C++.html?id=iQGGDwAAQBAJ&printsec=frontcover&source=kp_read_button&redir_esc=y#v=onepage&q&f=false
#include <iostream>
template <typename T>
class smart_ptr
{
struct deleter_base
{
virtual ~deleter_base() {};
virtual void apply(T* p) = 0;
};
template <typename Deleter>
struct deleter : public deleter_base
{
deleter(Deleter d): m_d(d) {}
void apply(T* p) override
{
m_d(p);
}
Deleter m_d;
};
deleter_base* m_db;
T* m_p;
char m_buf[16];
public:
template <typename Deleter>
smart_ptr(T* p, Deleter d)
: m_p(p)
, m_db( sizeof(Deleter) > sizeof(m_buf) ? new deleter<Deleter>(d) : new (m_buf) deleter<Deleter>(d))
{
}
~smart_ptr()
{
m_db->apply(m_p);
if (static_cast<void*>(m_db) == static_cast<void*>(m_buf))
{
m_db->~deleter_base();
}
else
{
delete m_db;
}
}
T& operator*() {return *m_p;}
const T& operator*() const {return *m_p;}
T* operator->() { return m_p; }
const T* operator->() const { return m_p; }
};
struct Test
{
Test(double d): m_d(d) { std::cout << "Test::Test" << std::endl; }
~Test() { std::cout << "Test::~Test" << std::endl; }
double m_d;
};
int main()
{
auto deleter = [](Test * t) {delete t;};
smart_ptr<Test> spd(new Test(3.6), deleter);
std::cout << spd->m_d << std::endl;
}
One question. When deleter does not fit inside local buffer we allocate memory for it and leave m_buf
uninitialized. Is it a bug or I miss something?
In the destructor we compare m_buf
which has random value against value returned by new deleter<Deleter>(d)
. It is not impossible that those values match, right?
Aucun commentaire:
Enregistrer un commentaire