将unique_ptr打印到cout

Hem*_*ava 8 c++ iostream smart-pointers unique-ptr c++11

无法理解为什么会失败?

int *p = new int(10);
std::unique_ptr<int> ptr(p);
// Below line gives compilation error.
std::cout << "Value of ptr        " << ptr << std::endl;
// Below line works well.
std::cout << "Value pointed ptr   " << *ptr << std::endl;
std::cout << "Value of ptr->get() " << ptr.get() << std::endl;
Run Code Online (Sandbox Code Playgroud)

我这样理解:

假设p的地址为100,新分配的内存地址为200.

p                new allocated memory
----------       ---------
   200              10
----------       ---------
100              200


ptr
----------
   200
----------
300
Run Code Online (Sandbox Code Playgroud)

在上面的描述中,unique_ptr指向新分配的内存本身,避免'p'.那么,不应该打印'ptr'给我200?

Mr.*_*C64 11

std::unique_ptr<int> ptr(p);
// Below line gives compilation error.
std::cout << "Value of ptr        " << ptr << std::endl;
Run Code Online (Sandbox Code Playgroud)

为了能够使用通常的<<语法来打印某个类的对象cout,必须实现适当的重载operator<<.

例如,如果您有一个类X,如果要启用cout << x语法,可以operator<<像这样重载:

#include <ostream> // for std::ostream

std::ostream& operator<<(std::ostream& os, const X& x)
{
  // Implement your output logic for 'x'
  ...

  return os;
}
Run Code Online (Sandbox Code Playgroud)

C++标准库设计者选择不实现这样的重载std::unique_ptr; 这就是当您尝试使用s <<实例时出现编译错误unique_ptr的原因.


Rei*_*ica 8

那么,打印 'ptr' 不应该给我 200 吗?

如果指定的标准库std::unique_ptr应该可以流式传输到标准流中,则应该如此。换句话说,应该存在operator <<for的重载std::unique_ptr

然而,该标准没有指定这样的事情,因此流式传输会unique_ptr导致编译错误(不operator <<接受它)。解决方案正如您所发现的:如果您需要流式传输指针,请获取指针:

stream << ptr.get()
Run Code Online (Sandbox Code Playgroud)

  • @MartinBonner 至于细化建议,我想到了 `std::vector&lt;bool&gt;` 。 (2认同)