VSCode+MinGW-64环境下使用cout输出std::unique_ptr编译报错问题求助
Hey there, this isn't a compiler issue at all—your VSCode + MinGW-64 setup is totally fine. The problem is that the C++ standard library doesn’t provide a built-in operator<< for directly printing a std::unique_ptr object with cout.
When you write cout << unPtr1;, the compiler can’t tell what exactly you want to output: the memory address the pointer holds, or the value it points to? You need to be explicit about it.
Here are the two common solutions depending on your goal:
1. Print the value stored in the unique_ptr
To get the integer value (25 in your case), dereference the unique_ptr just like a regular raw pointer:
#include <iostream> #include <memory> int main() { std::unique_ptr<int> unPtr1 = std::make_unique<int>(25); std::cout << *unPtr1; // Outputs 25 return 0; }
2. Print the memory address the unique_ptr points to
If you want to see the actual memory location (like 0x7ffeefbff5ac), use the get() method to retrieve the underlying raw pointer:
#include <iostream> #include <memory> int main() { std::unique_ptr<int> unPtr1 = std::make_unique<int>(25); std::cout << unPtr1.get(); // Outputs the pointer's memory address return 0; }
std::unique_ptr is a smart pointer wrapper, so it doesn’t implicitly convert to a type cout knows how to print—you have to explicitly access either the value or the raw pointer using the methods above.
内容的提问来源于stack exchange,提问作者José Gaspar

