Printing unique_ptr to cout(将UNIQUE_PTR打印到CUT)
本文介绍了将UNIQUE_PTR打印到CUT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无法理解此操作失败的原因?
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吗?
推荐答案
std::unique_ptr<int> ptr(p); // Below line gives compilation error. std::cout << "Value of ptr " << ptr << std::endl;
若要使用通常的<<
语法通过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;
}
C++标准库设计者选择不为std::unique_ptr
实现这样的重载;这就是当您尝试将<<
与unique_ptr
的实例一起使用时出现编译错误的原因。
这篇关于将UNIQUE_PTR打印到CUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:将UNIQUE_PTR打印到CUT


猜你喜欢
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- XML Schema 到 C++ 类 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- GDB 不显示函数名 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01