打印 unique_ptr 到 cout

Printing unique_ptr to cout

无法理解为什么会失败?

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;

我是这样理解的:

假设p的地址是100,新分配内存的地址是200。

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


ptr
----------
   200
----------
300

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

So, should not printing 'ptr' give me 200?

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

但是,标准没有指定这样的东西,因此流式传输 unique_ptr 会导致编译错误(没有 operator << 接受它)。解决方案如您所见:如果您需要流式传输指针,请获取指针:

stream << ptr.get()
std::unique_ptr<int> ptr(p);
// Below line gives compilation error.
std::cout << "Value of ptr        " << ptr << std::endl;

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

例如,如果你有一个 class 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;
}

C++ 标准库设计者选择不为 std::unique_ptr 实现这样的重载;这就是当您尝试将 <<unique_ptrs.

的实例一起使用时出现编译错误的原因