[PATCH v3] libstdc++: improve string construction from streambuf [PR112925]

Jonathan Wakely jwakely@redhat.com
Mon Nov 2 11:21:21 GMT 2026


On Wed, 28 Oct 2026 at 10:59 -0400, Nathan Myers wrote:
>Changes in v3:
> - Remove check for __is_constant_evaluated.
> - Gate the shortcut on string's _Traits matching the default,
>  like the streambuf iterator's traits.
>
>Changes in v2:
> - When constructing from a streambuf iterator range, ensure its
>  sentinel is another streambuf iterator, or default_sentinel.
> - Add #pragma diagnostic push for "if constexpr" in c++11.
> - Add c++11 test for construction from raw iterators.
> - Add test with a sentinel in place of default-ctor'd iterator.
> - Add test with range pipeline.
> - Remove spurious 'constexpr' in test.
>
>Constructing a string from a streambuf iterator pair or range has
>been found to be 3x faster using the streambuf member `sgetn`.
>This is the minimal implementation as outlined in [PR112925].
>Future improvements might include doing the same optimization
>when appending, and preallocating when the final size can be
>known.
>
>libstdc++-v3/ChangeLog:
>	PR libstdc++/112925
>	* include/bits/basic_string.h: (basic_string range ctor)

The colon should be after the closing paren not the filename.

>	Special-case ranges of streambuf iterators.
>	* include/bits/basic_string.tcc: (_M_construct) Special-case

Same here
(the 'git gcc-verify' alias should catch these).

>	streambuf iterators. These always consume the whole stream.
>	* testsuite/21_strings/basic_string/cons/char/from_sbufiter.cc:
>	New test, construction from two istreambuf_iterators.
>	* testsuite/21_strings/basic_string/cons/from_range2.cc:
>	New tests, construction from ranges.
>---
> libstdc++-v3/include/bits/basic_string.h      | 11 +++-
> libstdc++-v3/include/bits/basic_string.tcc    | 18 +++++++
> .../basic_string/cons/char/from_sbufiter.cc   | 24 +++++++++
> .../basic_string/cons/from_range2.cc          | 50 +++++++++++++++++++
> 4 files changed, 102 insertions(+), 1 deletion(-)
> create mode 100644 libstdc++-v3/testsuite/21_strings/basic_string/cons/char/from_sbufiter.cc
> create mode 100644 libstdc++-v3/testsuite/21_strings/basic_string/cons/from_range2.cc
>
>diff --git a/libstdc++-v3/include/bits/basic_string.h b/libstdc++-v3/include/bits/basic_string.h
>index fd9419220a4..6886c7b2632 100644
>--- a/libstdc++-v3/include/bits/basic_string.h
>+++ b/libstdc++-v3/include/bits/basic_string.h
>@@ -826,7 +826,16 @@ _GLIBCXX_BEGIN_NAMESPACE_CXX11
> 	basic_string(from_range_t, _Rg&& __rg, const _Alloc& __a = _Alloc())
> 	: basic_string(__a)
> 	{
>-	  if constexpr (ranges::forward_range<_Rg> || ranges::sized_range<_Rg>)
>+	  using _SbufIter = istreambuf_iterator<_CharT, char_traits<_CharT>>;
>+	  if constexpr (requires {
>+	    requires is_same_v<ranges::iterator_t<_Rg>, _SbufIter>;
>+	    requires is_same_v<ranges::sentinel_t<_Rg>, _SbufIter> ||
>+		     is_same_v<ranges::sentinel_t<_Rg>, default_sentinel_t>; })

Is the requires-expression used to short-circuit?

Is that worth it? We need to evaluate ranges::end(__rg) anyway, so the
sentinel_t alias is cheap to evaluate, and is_same_v is cheap.

So I think it is simpler to read without the requires requires, i.e.

         if constexpr (is_same_v<ranges::iterator_t<_Rg>, _SbufIter>
             && (is_same_v<ranges::sentinel_t<_Rg>, _SbufIter>
                 || is_same_v<ranges::sentinel_t<_Rg>, default_sentinel_t>))

Do we also need to gate on is_same_v<Traits, char_traits<_CharT>>
here, so that we don't take the _M_construct path unless it's going to
use the optimization? It probably doesn't matter, because if we have
an istreambuf_iterator and default sentinel then I think the
performance will be the same whether we use the loop in this function
or the loop in _M_construct for input iterators.

>+	    {
>+	      _M_construct(__rg.begin(), _SbufIter(), input_iterator_tag{});

This needs to be ranges::begin(__rg) because an arbitary range that
has istreambuf iterators might not have a .begin() member function.

>+	    }
>+	  else if constexpr (
>+	      ranges::forward_range<_Rg> || ranges::sized_range<_Rg>)

line break before the || rather than before the first condition
please:

       else if constexpr (ranges::forward_range<_Rg>
                           || ranges::sized_range<_Rg>)

> 	    {
> 	      const auto __n = static_cast<size_type>(ranges::distance(__rg));
> 	      reserve(__n);
>diff --git a/libstdc++-v3/include/bits/basic_string.tcc b/libstdc++-v3/include/bits/basic_string.tcc
>index de82e997888..5bfc26740c3 100644
>--- a/libstdc++-v3/include/bits/basic_string.tcc
>+++ b/libstdc++-v3/include/bits/basic_string.tcc
>@@ -199,6 +199,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
>
> 	_M_init_local_buf();
>
>+	// NB: size() (i.e. _M_length) is initialized only at the end.
> 	while (__beg != __end && __len < __capacity)
> 	  {
> 	    _M_local_buf[__len++] = *__beg;
>@@ -228,6 +229,23 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
> 		_M_data(__another.__ptr);
> 		_M_capacity(__capacity);
> 	      }
>+
>+#if __cplusplus >= 201103L
>+# pragma GCC diagnostic push
>+# pragma GCC diagnostic ignored "-Wc++17-extensions" // if constexpr
>+
>+	    using _SbufIter = istreambuf_iterator<_CharT, char_traits<_CharT>>;

This can just be istreambuf_iterator<_CharT> using the default
template argument, although maybe it's better to be more explicit that
we are intentionally using std::char_traits<_CharT>. So no change
needed.

>+	    if constexpr (is_same<_InIterator, _SbufIter>::value &&
>+			  is_same<_Traits, char_traits<_CharT>>::value)
>+	      {
>+		auto __r = std::__copy_n_a(
>+		  __beg, __capacity - __len, _M_data() + __len, false);

Line break after one of the commans, not after the opening paren.

It didn't occur to me before but this makes a copy of __beg and then
reads from that, then operates on the original __beg again. That's not
valid for input iterators in general, but I think it's OK for our
istreambuf_iterator ... right?

Although the copy of __beg is the one that gets _M_sbuf == nullptr,
when we do `__beg == __end` on the original object that will still be
true because it will use _M_sbuf->sgetc() which will return eof.

So I think it works by design not just by accident.

>+		__len = __r - data();
>+		continue;
>+	      }
>+
>+# pragma GCC diagnostic pop
>+#endif
> 	    traits_type::assign(_M_data()[__len++],
> 				static_cast<_CharT>(*__beg));
> 	    ++__beg;
>diff --git a/libstdc++-v3/testsuite/21_strings/basic_string/cons/char/from_sbufiter.cc b/libstdc++-v3/testsuite/21_strings/basic_string/cons/char/from_sbufiter.cc
>new file mode 100644
>index 00000000000..338dcbcdd27
>--- /dev/null
>+++ b/libstdc++-v3/testsuite/21_strings/basic_string/cons/char/from_sbufiter.cc
>@@ -0,0 +1,24 @@
>+// { dg-do run { target c++11 } }
>+
>+#include <string>
>+#include <sstream>
>+#include <iterator>
>+#include <streambuf>
>+#include <testsuite_hooks.h>
>+
>+std::string abcs{"abcdefghijklmnopqrstuvwxyz"};
>+std::string twice{abcs + " " + abcs};
>+
>+void
>+test_iters()
>+{
>+  std::istringstream stream{twice};
>+  std::istreambuf_iterator<char> iter{stream}, end;
>+  std::string str{iter, end};
>+  VERIFY(str == twice);
>+}
>+
>+int main()
>+{
>+  test_iters();
>+}
>diff --git a/libstdc++-v3/testsuite/21_strings/basic_string/cons/from_range2.cc b/libstdc++-v3/testsuite/21_strings/basic_string/cons/from_range2.cc
>new file mode 100644
>index 00000000000..7dd98b5c29b
>--- /dev/null
>+++ b/libstdc++-v3/testsuite/21_strings/basic_string/cons/from_range2.cc
>@@ -0,0 +1,50 @@
>+// { dg-do run { target c++23 } }
>+
>+#include <string>
>+#include <sstream>
>+#include <iterator>
>+#include <streambuf>
>+#include <ranges>
>+#include <testsuite_hooks.h>
>+
>+std::string abcs{"abcdefghijklmnopqrstuvwxyz"};
>+std::string twice{abcs + " " + abcs};
>+
>+void
>+test_range()
>+{
>+  std::istringstream stream{twice};
>+  std::istreambuf_iterator<char> it{stream}, end;
>+  std::ranges::subrange range{it, end};
>+  std::basic_string str{std::from_range, range};
>+  VERIFY(str == twice);
>+}
>+
>+void
>+test_sentinel()
>+{
>+  std::istringstream stream{twice};
>+  std::istreambuf_iterator<char> it{stream}, end;
>+  std::ranges::subrange range{it, std::default_sentinel};
>+  std::basic_string str{std::from_range, range};
>+  VERIFY(str == twice);
>+}
>+
>+void
>+test_take()
>+{
>+  std::istringstream stream{twice};
>+  std::istreambuf_iterator<char> it{stream}, end;
>+  std::ranges::subrange range{it, std::default_sentinel};
>+  std::basic_string str{std::from_range,
>+    range | std::views::take_while([](char c){ return c != ' '; }) };
>+  VERIFY(str == abcs);
>+}
>+
>+
>+int main()
>+{
>+  test_range();
>+  test_sentinel();
>+  test_take();
>+}
>-- 
>2.56.0
>
>



More information about the Libstdc++ mailing list