我创建了一个通用删除器模板,可用于创建unique_ptr<>()
子类型允许Deleter
不仅仅是delete ptr
.
它与默认优化标志(即-O0
),但是,当我使用-O3
the T & operator * ()
函数以某种方式返回0
而不是f_pointer
内容。
我想确保我们同意编译器中存在问题并且我的模板是正确的。以下是一段完整的代码,应该在 Ubuntu 16.04 和 Ubuntu 18.04 以及可能的其他版本下编译,只要它们支持 C++14(请参阅下面的测试 g++ 版本)。
// RAII Generic Deleter -- allow for any type of RAII deleter
//
// To break compile with:
// g++ --std=c++14 -O3 -DNDEBUG ~/tmp/b.cpp -o b
#include <memory>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
template<class T, T null_value, class D, D deleter>
class raii_generic_deleter
{
public:
class pointer
{
private:
T f_pointer = null_value;
public:
pointer(T p)
: f_pointer(p)
{
}
pointer(std::nullptr_t = nullptr)
: f_pointer(null_value)
{
}
explicit operator bool () const
{
return f_pointer != null_value;
}
bool operator == (pointer const rhs) const
{
return f_pointer == rhs.f_pointer;
}
bool operator != (pointer const rhs) const
{
return f_pointer != rhs.f_pointer;
}
T & operator * ()
{
return f_pointer;
}
};
void operator () (pointer p)
{
deleter(*p);
}
};
typedef std::unique_ptr<int,
raii_generic_deleter<int, -1, decltype(&::close), &::close>>
raii_fd_t;
int main(int argc, char * argv [])
{
int fd = -1;
{
raii_fd_t safe_fd;
std::cout << "default initialization: safe_fd = " << *safe_fd
<< std::endl;
fd = open("/tmp/abc.tmp", O_RDWR | O_CREAT, 0700);
std::cout << "fd = " << fd << std::endl;
safe_fd.reset(fd);
std::cout << "safe_fd after the reset(" << fd
<< ") = " << *safe_fd << std::endl;
}
if(fd != -1)
{
// assuming the safe_fd worked as expected, this call returns an error
//
int r = close(fd);
int e(errno);
std::cout << "second close returned " << r
<< " (errno = " << e << ")" << std::endl;
}
return 0;
}
(原文见raii_generic_deleter.h https://github.com/m2osw/snapwebsites/blob/master/libsnapwebsites/src/snapwebsites/raii_generic_deleter.h在 libsnap 网站中)
这是我使用时得到的输出-O0
(无优化):
default initialization: safe_fd = -1
fd = 3
safe_fd after the reset(3) = 3
second close returned -1 (errno = 9)
在这种情况下*safe_fd
来电返回-1
and 3
正如预期的那样。这调用了模板T & pointer::operator * ()
功能。
通过任何级别的优化(-O1
, -O2
, -O3
)输出如下所示:
default initialization: safe_fd = 0
fd = 3
safe_fd after the reset(3) = 0
second close returned -1 (errno = 9)
正如我们所看到的,安全文件描述符返回0
代替-1
初始化后然后再次0
当它应该是3
。但是,析构函数正确关闭文件,因为第二次关闭按预期失败。换句话说,不知何故,文件描述(3
) 是删除者已知并正确使用的。
当我以这种方式更新指针运算符时:
T & operator * ()
{
std::cout << "f_pointer within operator * = " << f_pointer
<< std::endl;
return f_pointer;
}
那么任何优化级别的输出都是正确的:
f_pointer within operator * = -1
default initialization: safe_fd = -1
fd = 3
f_pointer within operator * = 3
safe_fd after the reset(3) = 3
f_pointer within operator * = 3
second close returned -1 (errno = 9)
这可能是因为该特定功能没有得到完全优化。
编译器:
我在 Ubuntu 16.04 上使用 Stock g++ 进行了测试
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609
也在 Ubuntu 18.04 上
g++(Ubuntu 7.3.0-16ubuntu3)7.3.0
我也继续将其报告为GNU 网站上的错误 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86296.