Click here to Skip to main content
15,895,011 members
Articles / Programming Languages / C++

Unique_ptr custom deleters and class factories

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
18 Sep 2012CPOL3 min read 29.8K   65   6  
Making unique_ptr more user friendly.
// Article2.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <cstdlib>
#include <memory>
#include <functional>
#include <iostream>

// lambda deleters
auto NoDelete = [](char *)  { };
auto Free     = [](char *p) { free(p); };
auto Delete   = [](char *p) { delete p; };
auto ArDelete = [](char *p) { delete [] p; };

struct MyDeleter{
   // What should be the default?? No deleter? delete? I choose to
   // mimic the default of unique_ptr, shared_ptr.
   MyDeleter()
      : f( Delete )
   {}

   // allow the user to specif what type of deleter to use
   explicit MyDeleter(std::tr1::function< void(char *)> const &f_ )
      : f(f_)
   {}

   void operator()(char *p) const
   {
      f(p);
   }

private:
   std::tr1::function< void(char *)>   f;
};


typedef std::unique_ptr<char, MyDeleter>  Unique_Ptr_2;


Unique_Ptr_2 factory(int choice)
{
   static char dbyte[64] = "Never ever delete this or undefined behavior will occur";
   if( choice == 0 )
      return Unique_Ptr_2( dbyte,               MyDeleter(NoDelete) );
   else if( choice == 1 )
   {
      Unique_Ptr_2 p( new char,            MyDeleter(Delete) );
      *p = 'a';
      return p;
   }
   else if( choice == 2)
   {
      Unique_Ptr_2 p( (char *)malloc(512), MyDeleter(Free) );
      strcpy( p.get(), "malloc string" );
      return p;
   }
   else if( choice == 3 )
   {
      Unique_Ptr_2 p( new char[128],       MyDeleter(ArDelete) );
      strcpy( p.get(), "newed string" );
      return p;
   }

   return Unique_Ptr_2( nullptr,                MyDeleter() ); // any deleter should work with null
}

int main(void)
{
   Unique_Ptr_2 p0 = factory(0); // string
   std::cout << p0.get() << std::endl;

   Unique_Ptr_2 p1 = factory(1); // char
   std::cout << *p1      << std::endl;

   Unique_Ptr_2 p2 = factory(2); // string
   std::cout << p2.get() << std::endl;

   Unique_Ptr_2 p3 = factory(3); // string
   std::cout << p3.get() << std::endl;

   return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions