[PATCH] libstdc++: store the length after the store of the null character

Andrew Pinski andrew.pinski@oss.qualcomm.com
Wed Nov 19 00:54:37 GMT 2025


This improves the code generation slightly for std::string because of
aliasing. In many cases the length will be read again and the store of
the null character will cause the length to be re-read due to aliasing
requirements of the char type. So swapping around the stores will allow
the length not to have to be reloaded from memory and will allow
for more optimizations.

Bootstrapped and tested on x86_64-linux-gnu.

libstdc++-v3/ChangeLog:

	* include/bits/basic_string.h (basic_string::M_set_length): Swap
	around the order of traits_type::assign and _M_length so that
	_M_length is at the end.

Signed-off-by: Andrew Pinski <andrew.pinski@oss.qualcomm.com>
---
 libstdc++-v3/include/bits/basic_string.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libstdc++-v3/include/bits/basic_string.h b/libstdc++-v3/include/bits/basic_string.h
index 8ae6569f501..c4b6b1064a9 100644
--- a/libstdc++-v3/include/bits/basic_string.h
+++ b/libstdc++-v3/include/bits/basic_string.h
@@ -269,8 +269,8 @@ _GLIBCXX_BEGIN_NAMESPACE_CXX11
       void
       _M_set_length(size_type __n)
       {
-	_M_length(__n);
 	traits_type::assign(_M_data()[__n], _CharT());
+	_M_length(__n);
       }
 
       _GLIBCXX20_CONSTEXPR
-- 
2.43.0



More information about the Libstdc++ mailing list