Dec 17, 2014

[C++14] unique_ptr with type erasure as shared_ptr

Extra information:
Non-capturing C++ lambdas can be converted to a pointer to function, but what about the calling convention?

Wrapper for unique_ptr to have the same behavior as shared_ptr when dealing with derived types. i.e type erasure.
#include <iostream>
#include <memory>
#include <utility>
using namespace std;
template<typename T, typename U>
auto GetUniquePtr(U* ptr)
{
   auto deleter = [](auto ptr)
   {
       delete (U*)(ptr);
   };
  //RVO enabled.
   return unique_ptr<T, decltype(deleter)>{ptr, deleter}; 
   // use decltype(deleter) instead of void(*)(T*) for compiler
   // to deduce type
   /*return unique_ptr<T, void(*)(T*)>{ptr, deleter};
       using void(*)(T*) will force internal tuple to store a
       pointer to function , which is 1 word size! */
}
struct Base_1
{
   void ha()
   {
       cout << "coding is for fun!" << endl;
   }
   ~Base_1()
   {
       cout << "Base_1 destructor" << endl;
   }
};
struct Base_2 : Base_1
{
   ~Base_2()
   {
       cout << "Base_2 destructor" << endl;
   }
};
 
int main()
{
   auto u_ptr = GetUniquePtr<Base_1>(new Base_2);
   cout << sizeof(u_ptr) << endl; //same size as default deleter.
   u_ptr->ha();
}

No comments:

Post a Comment

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