C++中用cout输出unique_ptr出现编译错误是什么原因?
问题根因
- 编译报错的核心原因是C++标准库没有为
std::unique_ptr提供operator<<的默认重载实现,无法直接将unique_ptr对象传入std::cout输出 - 附加参数错误:你指定C++标准的编译参数写法有误,正确参数为
-std=c++11、-std=c++14,而非-std=g++11这类格式
修复方案
如果你的需求是输出unique_ptr持有内存的地址,调用get()方法获取它管理的原始指针再输出即可;如果是要输出指针指向的数值,使用*解引用即可(注意需先判断指针非空,避免空指针解引用崩溃)。
修复后完整代码如下:
#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 address: " << p1.get() << ", value: " << *p1 << '\n'; cout << "smart pointer 2 address: " << p2.get() << '\n'; cout << "move to p2\n"; p2 = move(p1); cout << "smart pointer 1 address: " << p1.get() << '\n'; cout << "smart pointer 2 address: " << p2.get() << ", value: " << *p2 << '\n'; cout << "free memory\n"; p2.reset(); cout << "smart pointer 1 address: " << p1.get() << '\n'; cout << "smart pointer 2 address: " << p2.get() << '\n'; return 0; }
编译命令参考
g++ 53-4.cpp -std=c++11 -o test
执行编译后的程序可以看到std::move执行后p1会变为空指针,reset执行后p2也变为空指针,符合unique_ptr独占所有权的语义。
内容的提问来源于stack exchange,提问作者Shrew
相关产品推荐
相关产品推荐

