【问题标题】:Am I using the pointer class properly in this generic unique_ptr<>() deleter?我是否在这个通用的 unique_ptr<>() 删除器中正确使用了指针类?
【发布时间】:2018-06-25 00:33:08
【问题描述】:

我创建了一个通用删除器模板,可用于创建 unique_ptr&lt;&gt;() 子类型,允许 Deleter 而不仅仅是 delete ptr

它适用于默认优化标志(即-O0),但是,当我使用-O3 时,T &amp; 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 libsnapwebsites)

当我使用-O0(没有优化)时,我得到了输出:

default initialization: safe_fd = -1
fd = 3
safe_fd after the reset(3) = 3
second close returned -1 (errno = 9)

在这种情况下,*safe_fd 调用按预期返回-13。这会调用模板T &amp; 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,然后在应该是3 时再次返回0。但是,析构函数会正确关闭文件,因为第二次关闭按预期失败。换句话说,不知何故,文件描述 (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

我也将此事报告为bug on the GNU website

【问题讨论】:

  • 这不能用 libc++ 编译。
  • @n.m.它没有编译器或链接?您在什么操作系统上尝试过?
  • 由于 const 正确性而无法编译。在 Linux 和 cygwin 上试过。可以通过使 f_pointer 可变和 operator* 成为返回非常量 ref 的 const 成员函数来修复(如果您考虑一下,这是合理的)。但这并不影响主要问题。
  • 我的代码是基于这个stackoverflow.com/questions/15756960/…,它有一个非常量的T &amp; operator * () 函数,我还没有找到关于正确实现pointer 类的好文档。
  • 更正,值初始化似乎执行正常,但 opeeator* 看起来已损坏。

标签: c++ templates g++ ubuntu-16.04 unique-ptr


【解决方案1】:

问题似乎是由于 unique_ptr::operator* 的 libstdc++ 实现。这是一种非常简化、精简的方式:

struct pointer
{
    pointer(int val = -42) : z(val) { }
    int z = -42;
    int& operator*() { return z; }
};

struct my_unique_ptr
{
    pointer rep;
    pointer get() { return rep; }
#ifdef PROBLEM
    int& operator*() { return *get(); } // libstdc++ implementation
#else
    int& operator*() { return *rep; } // libc++ implementation
#endif
};

int main()
{
    my_unique_ptr q;
    std::cout << *q << "\n";
}

现在很清楚,libstdc++ 不可能与您的pointer 实现一起使用,因为它返回对来自operator* 的本地临时对象的引用。任何存储自己的指针的pointer 都会遇到同样的问题。

按照标准,这似乎不是 libstdc++ 中的错误。标准规定unique_ptr::operator*() 返回*get(),libstdc++ 忠实地这样做了。

如果有的话,这是标准中的缺陷。

立即解决方法是停止在 pointer 类中定义 operator*unique_ptr 不需要它(NullablePointer 不需要提供它)。

由于pointer 实际上只不过是T 的包装器,它为给定的常量提供值初始化,因此为它定义一个operator T() 并使用get() 来“取消引用”对应的unique_ptr

【讨论】:

  • NulablPointer 没有定义operator * (),但没有它我无法编译。 (/usr/include/c++/5/bits/unique_ptr.h:291:9: error: no match for 'operator*') 拥有operator T ()get() 不会帮助。我只是认为目前不可能那样使用unique_ptr&lt;&gt;()...
  • 它不能编译只是因为你使用了operator*。如果你删除所有*save_fd*p,它编译得很好(检查了 3 个版本的 gcc 和 2 个 clang)。分别替换为int(save_fd,get())T(p)
  • int&amp; operator*() { return A_MEMBER; } 在不检查技术上是否正确的情况下,这看起来像是对“指针”概念的严重滥用。 即使某些标准文本说它是正确的,也并不意味着它本来就是这样的。或者它仍然会在未来的修订版中得到“支持”(理论上)。 (我也讨厌输入运算符的语义,但至少每个人都知道它们是非常退化的前向迭代器形式,并且使用模式是刻板的。)
【解决方案2】:

我正在添加我自己的答案,以向对此类 RAII 删除器感兴趣的其他人显示代码中的更改(非常实用,因为您无需在每次实例化时都指定删除器!)。

正如@n.m 所述。在接受的答案中,int 不是指针,因此不能作为指针访问。所以T &amp; operator * () 对于这种类型是不合逻辑的(因为operator [] ()operator -&gt; () 也没有意义)。

代码的问题是因为operator * ()unique_ptr&lt;&gt;() 实现中使用了get()。它看起来像这样:

/// Return the stored pointer.
pointer
get() const noexcept
{ return std::get<0>(_M_t); }

如我们所见,get() 返回一个pointer 副本。这样的对象是暂时的!这意味着您不能从中返回引用并希望它保持有效。不过,operator * () 会这样做:

/// Dereference the stored pointer.
typename add_lvalue_reference<element_type>::type
operator*() const
{
  _GLIBCXX_DEBUG_ASSERT(get() != pointer());
  return *get();
}

如我们所见,该函数返回get() 返回的引用内容,但随后表示它需要引用。这就是为什么我的operator * () 实现必须返回一个非常量引用。

通过删除该约束并使用operator T () const 而不是operator * () 来检索unique_ptr&lt;&gt;() 的值,我得到了正确的值。

// 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;
        }

        operator T () const
        {
            return f_pointer;
        }
    };

    void operator () (pointer p)
    {
        deleter(static_cast<T>(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.get()
                  << 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.get() << 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;
}

所以两个主要变化(1)T &amp; operator * () 变成了operator T () const 和(2)main(),把*safe_fd 变成safe_fd.get()

注意:我还将 f_pointer 转换为 T 用于删除函数,以防删除函数不是一对一匹配并且自动投射会失败。 (即在我的情况下,close(int) 有一个精确的 T 作为输入,所以它可以正常工作。有时删除器可能不是那么完美。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 2019-03-14
    相关资源
    最近更新 更多