r/cpp • • Jun 25 '26

std::formatter specialization for smart pointers

Currently something like

std::unique_ptr<int> u_ptr = std::make_unique<int>(42);
std::shared_ptr<int> s_ptr = std::make_shared<int>(42);
std::println("uptr: {}", u_ptr);
std::println("sptr: {}", s_ptr);

is ill formed because there is no specialization of std::formatter for smart pointer types.

On the other hand,

std::cout << "uptr: " << u_ptr << '\n';
std::cout << "sptr: " << s_ptr << '\n';

do work because ostream defines overloads for smart pointer types.

Please let me know if anyone has thoughts or if there's some reason that these types haven't been specialized that I'm missing.

16 Upvotes

19 comments sorted by

View all comments

Show parent comment

6

u/MFHava WG21|🇦🇹 NB|P3049|P3625|P3729|P3786|P3813|P4216 Jun 26 '26

trying to find the \0 leads to unsafe memory access?

Exactly!

format specialization explicitly casts to const void *

Only sane design ...