C++ Logo

std-discussion

Advanced search

Re: format_to (a char array) easy to misuse

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Sun, 02 Oct 2022 14:42:25 +0100
Hi,

I think it would have been way better if the algorithms worked with output ranges, rather than output iterators. A back_inserter output range could have an unreachable sentinel. People could opt-in to no bound checking with a pointer by explicitly creating a subrange with unreachable sentinel.

There is also no one liner to create a bound-checked output iterator. And the only way to signal out-of-bounds is with an exception. I am absolutely not a fan.

But my vague recollection is that people didn't like std::ranges::copy(input_range, output_range), which is more of a naming problem IMO.

Cheers,
Lénárd

On 2 October 2022 12:32:54 BST, Marcin Jaczewski via Std-Discussion <std-discussion_at_[hidden]> wrote:
>niedz., 2 paź 2022 o 10:35 Olaf van der Spek via Std-Discussion
><std-discussion_at_[hidden]> napisał(a):
>>
>> Hi,
>>
>> This snippet overflows the destination buffer. Is format_to too easy to misuse?
>> Shouldn't it requires an iterator to the end so it could avoid this issue?
>> It seems like a modern equivalent of fgets()
>>
>> #include <format>
>> #include <iostream>
>>
>> int main()
>> {
>> char d[10] = {};
>> std::format_to(d, "0123456789 {}", 42);
>> std::cout << std::string_view(d, 10) << std::endl;
>> }
>
>This is more of a problem with raw pointers than this function.
>Example on https://en.cppreference.com/w/cpp/utility/format/format_to
>show `std::back_inserter(buffer)`.
>There are multiple algorithms that work only with a single output iterator.
>
>Question is should standard add a new adapter for input iterator for
>filling bound ranges?
>Something like `std::range_fill(std::ranges::range auto& x)` that
>returns an output iterator that thrown when you try
>write past the end.
>
>> --
>> Std-Discussion mailing list
>> Std-Discussion_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>--
>Std-Discussion mailing list
>Std-Discussion_at_[hidden]
>https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion

Received on 2022-10-02 13:42:34