c++ - std::unique_ptr ostream 插入器

标签 c++ c++11 ostream unique-ptr

我在 gcc 4.4.6 中使用 -std=c++0x 选项启用了 unique_ptr。它看起来工作得很好并且正是我所需要的——一个带有自定义删除器的范围指针。

但是我确实注意到了一个问题。

typedef std::unique_ptr<X> XPtr;

XPtr ptr1(new X);
XPtr ptr2(new X);

std::cout << "ptr1 points to " << ptr1 << std::endl;
std::cout << "ptr2 points to " << ptr2 << std::endl;

显示: ptr1 指向 1 ptr2 指向 1

我认为 ostream 插入器正在插入 bool 值。

下面修复了它,但我想知道这是否不应该成为标准库的一部分。

template<typename Target, typename Deleter>
std::ostream & operator <<( std::ostream & out, const std::unique_ptr<Target, Deleter> & value)
{
    // output the raw pointer
    out << value.get();
    return out;
}

所以问题是:这是 gcc 中当前 unique_ptr 实现的限制,还是我对 unique_ptr 的期望过高?

最佳答案

这似乎是 gcc 4.4.6 附带的库中的错误。转换是

explicit operator bool() const noexcept;

并且不应通过尝试将指针插入 。这应该会导致编译错误,那就是 在 gcc 4.7 上究竟发生了什么。

编辑: gcc 4.4 不支持显式转换运算符,因此这在当时不起作用。您应该获得更新的 gcc 版本才能真正使用 C++11。

关于c++ - std::unique_ptr ostream 插入器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10537369/

相关文章:

c++ - C++ 11 thread_local变量是否自动静态?

c++ - 哪些 Windows C++ IDE 支持新的 C++0X 标准?

c++ - 在 STL vector 数组中初始化类

c++ - 与 'operator<<' 不匹配(操作数类型为 'std::ostream {aka std::basic_ostream<char>}'

c++ - 在 MSVC 的 Debug模式下分配给 std::future 时崩溃

c++ - 在 C++ 中,如何传递一些参数而将其他参数保留为默认值?

c++ - 使数据进入 ostream 以进入字节数组的最有效方法是什么?

c++ - 使用 ostream 和链接的运算符重载。为什么要通过引用返回?

c++ - 不可 move -不可复制对象的 vector 的 move 分配不编译

C++:Boost::mutex在同一范围内单独锁定多个变量