C++ Logo

std-proposals

Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Sun, 31 Jan 2021 17:26:33 -0500
On Sun, Jan 31, 2021 at 5:00 PM Dvir Yitzchaki via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> 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 the one hand, that's not possible because the stream iterators only
take non-`const` lvalue references to the stream. On the other hand,
that makes the code that the OP wants to write impossible anyway, so
the feature the OP wants wouldn't help.

But yes, this is a good reason why you shouldn't be able to pass a
prvalue to stream iterators.

Received on 2021-01-31 16:26:47