3

我有一个结构

typedef struct myStruct_st
{
  int a;
}myStruct;

它可以使用创建

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

并删除使用

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

我希望为结构分配的内存自动释放

为此,我写了一个模板

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 *);
};

并像那样使用它

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

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

  return 0;
}

如何使用 stl 或 boost 使其成为更标准的方式?

4

2 回答 2

3

Boost 的 shared_ptr 用几乎相同的代码做几乎相同的事情。

#include <boost/shared_ptr.hpp>

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

    ptr_st->a = 11;
}

但是您应该考虑是要编写 C++ 代码还是 C 代码。您正在使用一些非常 C 风格的语法(typdef structclass在声明前,使用“新函数”而不是构造函数,使用“自由函数”而不是析构函数),但是您标记了这个 C++ 并且显然您正在使用一些 C++ 特性。如果您想使用 C++,请使用它的所有功能,如果您不想这样做,请坚持使用 C。将两者混合过多会给任何试图弄清楚您的代码的人造成很多混乱(和你的“设计决定”)。

于 2010-07-16T10:29:55.037 回答
1

I know this is an old post but I just found it and I figure others probably will also. I'm also looking for an auto_ptr style smart pointer but which takes a deleter object and for the same reason as the OP, I'm also using the openssl library and want to wrap the resource. I am using boost::shared_ptrs with deleters() for managing openssl objects but I found out the hard way that you have to be careful because some of the openssl calls take ownership of the pointers you pass them. This can cause a problem if you are storing it in a shared_ptr because you then end up with a double-delete scenario. Also, semantically I don't actually want to "share" ownership of this objects with anyone. My usage has been either "I own it" or "I want to give it to someone else".

The new C++0x unique_ptr<> may offer a solution but in the mean time use shared_ptr carefully with openssl objects, it could bite you.

于 2011-11-17T17:28:30.350 回答