C++ Logo

std-proposals

Advanced search

Fwd: A 'stream()' member for std::ostream_iterator and cousins

From: Marco Fantozzi <marco.fantozzi_at_[hidden]>
Date: Mon, 1 Feb 2021 09:10:19 +0100
Sorry, but I fail to see why the above is more dangerous than taking a
reference to a member of any temporary...

Cheers.


Il giorno dom 31 gen 2021 alle ore 23:00 Dvir Yitzchaki <dvirtz_at_[hidden]>
ha scritto:

> this is dangerous because it’s easy to create a dangling reference if not
> consumed immediately, e.g.
>
> template<typename T>
> std::string print_vector( const vector<T> & v )
> {
> const auto& stream = copy( begin(v), end(v), ostream_iterator<int>( stringstream{}, ", " ) ).stream();
> return stream.str(); // dangling
> }
>
>
> On Sun, 31 Jan 2021 at 18:26, Marco Fantozzi via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>
>> Hello,
>>
>> I'm new to the newsletter, so I might not be in line with standard
>> netiquette here... In case please make me aware of my shortcomings, thanks
>> :-)
>>
>>
>> I noticed that it is not possible to retrieve the output stream used by a
>> std::ostream_iterator,
>> even if it would be useful in a few contexts like the following example:
>>
>> std::string print_vector( const std::vector<int> & v )
>> {
>> std::stringstream s;
>> copy( begin(v), end(v), std::ostream_iterator<int>( s, ", " ) );
>> return s.str();
>> }
>>
>> If there was a method ostream_iterator<...>::stream() that returns the
>> reference to the stream captured by the iterator,
>> it would be possible to make the above code more concise:
>>
>> template<typename T>
>> std::string print_vector( const vector<T> & v )
>> {
>> return copy( begin(v), end(v), ostream_iterator<int>( stringstream{},
>> ", " ) ).stream().str();
>> }
>>
>> Naturally the extension should apply to all input/output iterator facades
>> in the STL
>>
>> Thanks
>>
>> --
>> Trinetra
>> --
>> Std-Proposals mailing list
>> Std-Proposals_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>>
>

-- 
Marco Fantozzi
-- 
--
Marco Fantozzi
cell +39 320 9322942

Received on 2021-02-01 02:10:41