为用户定义对象指针的内存管理编写安全包装器 class

Writing a safe wrapper class for memory management of a user-defined object's pointer

我正在使用 redis c++ client 开发将在 redis 集群上执行 CRUD 操作的客户端 API。每当执行命令时,我使用的客户端库 returns 是 redisReply 结构的指针。后来,我希望在指针上使用freeReplyObject()函数来释放内存。

为了开发更安全的方式,让我不小心在无效指针上使用freeReplyObject(),我正在考虑写一个包装器class:

class reply_wrapper
{
        public:
                redisReply* p_reply;
                reply_wrapper(redisReply* reply = NULL)
                {
                        p_reply=reply;
                }

                ~reply_wrapper()
                {
                        freeReplyObject(p_reply);
                }
};

我正在考虑构建这个 class 的对象,每当我在服务器上执行命令时。我认为通过这样做我将不再需要手动释放内存。这种方法在这里是否正确,是否有更好的方法?

请注意 freeReplyObject() 处理 null 指针的情况。


I'm getting almost all the suggestions about using shared-pointer/unique-pointer. While I check the examples available online and see how it fits my scenario(custom destructor), I would also like to know if there's anything fundamentally wrong in my method of handling the memory above.


正如建议的那样,我使用了 std::unique_ptr 并且在构建它时我必须传递一个在其中调用 freeReplyObject 函数的仿函数。

struct redisReplyDeleterFunctor {
      void operator()(redisReply* p) {
          freeReplyObject(p);
      }
  };

unique_ptr<redisReply, redisReplyDeleterFunctor> reply((redisReply*)(redisClusterCommand(getDbContext(),  command.c_str())));

现在我不需要手动调用 freeReplyObject(),一旦我的 unique_ptr 超出范围,内存就会自动释放。