std::unique...::operator<<(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

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 β€” a std::basic_ostream to insert p into.
  • p β€” the pointer to be inserted into os.

πŸŽ€ 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