Printing unique_ptr to 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 吗?
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
的实例一起使用时会出现编译错误。
那么,打印"ptr"不应该给我 200 吗?
如果指定的标准库std::unique_ptr
应该可以流式传输到标准流中,则应该这样做。换句话说,应该存在std::unique_ptr
operator <<
超载。
但是,该标准没有指定这样的事情,因此流式传输unique_ptr
会导致编译错误(没有operator <<
接受它(。解决方案就像你发现的那样:如果你需要流式传输指针,请获取指针:
stream << ptr.get()
问题是在 C++20 之前,unique_ptr
没有重载operator<<
。
但从C++20开始,有的,从unique_ptr可以看出:
将template< class CharT, class Traits, class Y, class D > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::unique_ptr<Y, D>& p );
p
管理的指针的值插入到输出流os
中。相当于
os << p.get()
.
这意味着,std::cout << ptr;
将在 C++20(及以后(中工作。
演示
相关文章:
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- C++ Singleton - Prevent ::instance() to variable
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- std::cout.imbue()多重调用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- Visual Studio Code "undefined reference to `WinMain@16'"
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 如何解决"invalid conversion from 'char' to 'const char*'"
- Printing unique_ptr to cout
- 尝试用C++编码时,我收到一长串错误,例如"/tmp/ccloHU4h.o:dad.cpp:(.text+0x5c): undefined reference to `std::cout'"
- C++ std::this_thread::get_id() passing to cout
- CIN and COUT alternative to QT
- 错误"undefined reference to 'std::cout'"
- CString to std::cout
- "n" 或 'n' 或 std::endl to std::cout?
- "cout formatting options to print out currency values." 这是什么意思,我该怎么做?
- printf( "%cx" , FILE2CHAR(F(fr))) to cout
- 如何打印 map<string、map<int、int>> to cout 的内容?
- Display to cout使用g++停止执行