增强智能指针与自定义删除程序 [英] boost smart pointer with custom deleter
问题描述
我可以理解, boost :: shared_ptr
在调用自定义删除函数之前不会验证 NULL
但是我该如何实现呢?这将帮助我避免为 fclose
或没有(正确)指定行为的任何函数编写哑解包。
我的提升: #define BOOST_VERSION 104500
。这不是C ++ 11(因为我使用boost)。
问题是关于: make shared_ptr不使用删除
示例代码:
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文件));
}
...
boost :: shared_ptr< FILE>文件(safe_fopen(FILE_DOWNLOAD,rb),safe_fclose);
...
//现在它被创建=>再次打开它
file.reset(safe_fopen(FILE_DOWNLOAD,rb),safe_fclose);
EDIT
我的问题最初有关于使用 shared_ptr
的第二部分:为什么提供deleter作为函数参数而不是模板参数?显然,答案在这里:为什么unique_ptr需要两个模板参数,当shared_ptr只有一个? C ++ 11答案是unique_ptr,但为什么boost不提供一个 - 我们永远不会知道。
一个想法可能不是试图保护析构函数,你应该在构建时强制失败,从而避免在破坏期间检查无效。
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(...); //检查errno
返回文件;
}
但这并不能帮助修复未初始化的 boost :: shared_ptr
如果由于某种原因仍然发生的地方。
与使shared_ptr不使用删除
我认为由于功能的性质,你只是坚持使用这些较长的包装。
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.
My boost: #define BOOST_VERSION 104500
. This is not C++ 11 (since I use boost).
The question is related to: make shared_ptr not use delete
Sample 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);
EDIT
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;
}
However this doesn't help fix an un-initialized boost::shared_ptr
if that where to still happen for some reason.
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屋!