加强与定制删除智能指针 [英] boost smart pointer with custom deleter

查看:138
本文介绍了加强与定制删除智能指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以理解,的boost :: shared_ptr的调用定制删除函数之前不会验证 NULL ,但我怎么能做到这一点?这将帮助我避免 FCLOSE 或不(正确)指定行为的任何功能写哑包装。

I can understand that boost::shared_ptr doesn't validate for NULL before calling a custom deleter function, but how can I achieve this? This will help me avoid writing dumb wrappers for fclose or any function that doesn't (rightly) specify the behaviour.

我的提振:的#define BOOST_VERSION 104500 。这不是C ++ 11(因为我使用boost)。

My boost: #define BOOST_VERSION 104500. This is not C++ 11 (since I use boost).

问题是涉及到:让shared_ptr的不使用删除

样code:

static inline
FILE* safe_fopen(const char* filename, const char* mode)
{
      FILE* file = NULL;
      (void)fopen_s(&file, filename, mode);
      return file;
}

static inline
void safe_fclose(FILE* file)
{
      if (file)
         BOOST_VERIFY(0 == fclose(file));
}

...

boost::shared_ptr<FILE> file( safe_fopen(FILE_DOWNLOAD, "rb"), safe_fclose);
...
//    now it is created => open it once again
file.reset( safe_fopen(FILE_DOWNLOAD, "rb"), safe_fclose);

修改

我的问题最初有关于使用的shared_ptr 的第二部分:为什么提供的删除作为函数参数,而不是一个模板参数?显然,答案就在这里:<一href=\"https://stackoverflow.com/questions/21355037/why-does-unique-ptr-take-two-template-parameters-when-shared-ptr-only-takes-one/\">Why不取的unique_ptr两个模板参数时的shared_ptr只需要一个 C ++ 11的回答是的unique_ptr,但为什么升压我以前不提供对一个 - ?我们永远不会知道

My question initially had a second part concerning the use of shared_ptr: why providing the deleter as a function parameter instead of a template parameter? Apparently, the answer is here: Why does unique_ptr take two template parameters when shared_ptr only takes one? C++ 11 answer is unique_ptr, but why boost did't provide one - we'll never know.

推荐答案

一个想法也许不是试图保护的析构函数,你应该强制在建设的失败,从而避免其破坏过程中检查无效。

One thought was perhaps instead of trying to protect the destructor, you should force the failure at construction, thus avoiding having to check an invalid during destruction.

static inline
FILE* safe_fopen(const char* filename, const char* mode)
{
      FILE* file = NULL;
      (void)fopen_s(&file, filename, mode);
      if (!file)
         throw std::exception(...); // check errno
      return file;
}

然而,这并不能帮助解决未初始化的boost :: shared_ptr的如果这哪里还是发生了一些原因。

However this doesn't help fix an un-initialized boost::shared_ptr if that where to still happen for some reason.

shared_ptr的不使用删除
我认为,由于你只是坚持有这些较长的封装职能的性质。

Unlike make shared_ptr not use delete I think due to the nature of the functions you are just stuck with having these longer wrappers.

这篇关于加强与定制删除智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆