【发布时间】:2021-08-08 11:27:37
【问题描述】:
我现在正在研究智能指针,我只是在书中构建了示例代码。
但是当我像下面的代码一样使用unique_ptr 时,它会产生编译错误。错误码太长了,差点被剪掉了,写不完。
我想知道为什么这些代码出错了...请帮助我。
compiler and OS : g++ (Ubuntu 9.1.0-2ubuntu2~18.04) 9.1.0
我能找到的错误代码
/workspace/What_I_Learned/Cpp/53/53-4.cpp:23:30: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘std::unique_ptr<int>’)
23 | cout << "smart pointer 2: " << p2 << '\n';
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^~ ~~
| | |
| std::basic_ostream<char> std::unique_ptr<int>
/usr/include/c++/9/ostream:691:5: error: no type named ‘type’ in ‘struct std::enable_if<false, std::basic_ostream<char>&>’
我写的代码
#include <iostream>
#include <memory>
using namespace std;
int main(void) {
unique_ptr<int> p1(new int(10));
unique_ptr<int> p2;
cout << "smart pointer 1: " << p1 << '\n';
cout << "smart pointer 2: " << p2 << '\n';
cout << "move to p2\n";
p2 = move(p1);
cout << "smart pointer 1: " << p1 << '\n';
cout << "smart pointer 2: " << p2 << '\n';
cout << "free memory\n";
p2.reset();
cout << "smart pointer 1: " << p1 << '\n';
cout << "smart pointer 2: " << p2 << '\n';
}
我已经尝试过-std=g++11 和-std=g++14。
【问题讨论】:
-
而不是提供来自编译器的最后一条错误消息(位于屏幕或窗口底部的那个),而是提供第一条错误消息。这可能会提供更多有关问题原因的信息。一般来说,当编译器在你的代码中遇到更多错误时,它会变得更加混乱——这意味着第一个错误消息之后的错误消息更可能不清楚。无论如何,C++ iostream 不支持
std::unique_ptrs 的输入或输出。 -
您要打印什么?地址还是内容? (顺便说一句,哪本书?)
-
您是否要打印指针本身?然后使用例如
p1.get()。或者创建一个<<重载,将std::unique_ptr模板作为第二个参数(通过(常量)引用!)并使用其get函数来获取原始指针。 -
@Peter 感谢您提供的信息。我想把所有的错误从头到尾都写完,但是太长了,控制台窗口把它剪掉了将近 80%……我无法粘贴它。
-
标签: c++ c++11 operator-overloading smart-pointers unique-ptr