std::unique...::operator<<(3)
hey bestie π welcome to the std::unique...::operator<<(3) page β the function itself is std::unique_ptr::operator<< β folded in from the C++ Standard Libary manual (yes, that spelling is the manual name, iykyk). This is the little overload that lets you stream a std::unique_ptr and see the pointer it manages. Slay. β¨
πΈ NAME πΈ
std::unique_ptr::operator<<βstd::unique_ptr::operator<<(the icon, the moment, the whole NAME line)
β¨ Synopsis β¨
The signature is giving template realness, and the (since C++20) note is literally sitting in the middle of it in the source β here it is, line breaks and all:
template< class CharT, class Traits, class Y, class D >
std::basic_ostream<CharT, Traits>& operator<<(
std::basic_ostream<CharT, Traits>& os,
(since C++20)
const
std::unique_ptr<Y, D>& p );
This overload is since C++20. It inserts the value of the pointer managed by p into the output stream os.
It's equivalent to:
os << p.get();
π«Ά This overload participates in overload resolution only if os << p.get() is a valid expression. No valid expression, no participation β periodt.
π Parameters π
osβ astd::basic_ostreamto insertpinto.pβ the pointer to be inserted intoos.
π Return value π
It returns os. That's it. The stream comes back to you like a boomerang. πͺ
π¦ Notes π¦
Okay bestie, listen carefully because this is the plot twist π: if std::unique_ptr<Y, D>::pointer is a pointer to a character type (e.g., when Y is char([]) or CharT([])), this may end up calling the overloads of operator<< for null-terminated character strings β causing undefined behavior if the pointer does not in fact point to such a string π β rather than the overload for printing the value of the pointer itself.
π undefined behavior is not a vibe. If your pointer is character-y, make sure it actually points at a null-terminated string before you let this overload do its thing.
π Example π
This is the example, copied exactly, because we do not mess with code:
// Run this code
#include <iostream>
#include <memory>
class Foo {};
int main()
{
auto p = std::make_unique<Foo>();
std::cout << p << '\n';
std::cout << p.get() << '\n';
}
β Possible output
0x6d9028
0x6d9028
π See also π
getβ returns a pointer to the managed object (public member function).
That's the whole page, bestie π«Ά. Source/version/date sign-off: from http://cppreference.com, dated 2024.06.10, for std::unique...::operator<<(3). Stay slay, stay stream-safe. π
β¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms