tags:

views:

35

answers:

1

I have a structure

typedef struct myStruct_st
{
  int a;
}myStruct;

It can be created using

myStruct * myStruct_new()
{
  printf("Allocate\n");
  return new myStruct;
}

And deleted using

static void myStruct_free(myStruct * ptr)
{
  printf("Deallocate\n");
  delete ptr;
}

I want the memory allocated for the structure freed automatically

To this end, I wrote a template

template <class T>
class scoped_del
{
 public:
  scoped_del(T * p, void (*mfree)(T *)) :
   p_(p),
   mfree_(mfree)
  {
  }

  ~scoped_del()
  {
   mfree_(p_);
  }

 private:

  T * p_;

  void (*mfree_)(T *);
};

And use it like that

int main()
{
  myStruct * st = myStruct_new();

  class scoped_del<myStruct> ptr_st(st, myStruct_free);

  return 0;
}

How can I make it a more standard way using stl or boost?

+2  A: 

Boost's scoped_ptr does pretty much the same thing, in pretty much the same code.

#include <boost/scoped_ptr.hpp>

main() {
    boost::scoped_ptr<myStruct> ptr_st(myStruct_new(), myStruct_free);

    ptr_st->a = 11;
}

But you should consider whether you want to be writing C++ code or C code. You're using some very C-style syntax (typdef struct, class in front of declarations, using a "new function" instead of a constructor, using a "free function" instead of a destructor), but you tagged this C++ and clearly you are using some C++ features. If you want to use C++, use all of it's features, and if you don't want to do that then stick with C. Mixing the two too much is going to cause a lot of confusion for anyone trying to figure out your code (and your "design decisions").

SoapBox
I am using openssl library in c++ code and just wanted to find an easy way to autodelete openssl's structures without wrapping it into classes.
Max
Max
ok, it all right, but with shared_ptr instead of scoped_ptr:boost::shared_ptr<myStruct> ptr_st(myStruct_new(), myStruct_free);
Max
`boost::scoped_ptr` cannot use deleter.
big-z