将UNIQUE_PTR打印到CUT [英] Printing unique_ptr to cout
本文介绍了将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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文