r/cpp • u/SPEKTRUMdagreat • 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
u/Gorzoid Jun 25 '26
p1636 proposed adding one, didn't make C++20 due to disagreement with std::filesystem::path formatting.
p2693 adds a some of the specializations introduced above, but explicitly calls out why smart pointers are not included:
> Why not std::error_code/bitset/smart pointers? These don’t seem sufficiently useful to be processed as part of NB comments. Moreover, there were plans to remove smart pointer formatters from P1636 for consistency with raw pointers which are intentionally not formattable by default.
10
u/MFHava WG21|🇦🇹 NB|P3049|P3625|P3729|P3786|P3813|P4216 Jun 26 '26
Yeah... as it turns out those may not have been the best idea...
They are specified as
os << ptr.get();which has some "funny" side-effects forsmart_ptr<char>andsmart_pointer<char[]>...3
u/_Ilobilo_ Jun 25 '26
I don't see how that could be useful. you can always get the raw pointer or dereference it
2
u/bearheart Jun 25 '26
It’s fairly easy to write a formatter specialization for whatever you want
1
u/_Noreturn Jun 25 '26
I guess they aren't included because you have to cast the type to void*
1
u/aearphen {fmt} Jun 29 '26
Formatting of pointers is weird because it is not always clear if they should be formatted as pointer values or as objects pointed to (e.g. `[const] char*`). To avoid this and since the pointer values is not super useful, formatting of non-void pointers is disallowed by default. The same logic applies to smart pointers.
1
u/filipsajdak Jul 04 '26
Check this https://wrocpp.github.io/posts/format-smart-pointers/
1
u/No-Dentist-1645 Jun 25 '26
There's no real use case for that imo. If you want the actual raw pointer address, then you would use the raw pointsr