Scoped_ptr for a structure with a substituted free method

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 to be automatically freed

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 in a more standard way using stl or boost?

+3
source share
2 answers

Boost shared_ptr does almost the same thing, in almost the same code.

#include <boost/shared_ptr.hpp>

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

    ptr_st->a = 11;
}

, ++ C. C- (typdef struct, class , "" " ", " " ), ++ , , ++. ++, , , C. , ( " " ).

+3

, , , , , , . auto_ptr, deleter , OP, openssl . boost::shared_ptr deleters() openssl, , , openssl , . , shared_ptr, . , "" -. " ", " - ".

++ 0x unique_ptr<> , shared_ptr openssl, .

+1

Source: https://habr.com/ru/post/1754967/


All Articles