From 60fcd0db87747f8ae189f07dd7d2e1344b46c4ed Mon Sep 17 00:00:00 2001 From: Krystian Stasiowski Date: Sat, 21 Dec 2019 19:06:19 -0500 Subject: [PATCH] Make data_impl constexpr for zero-size strings --- .../static_string/detail/static_string.hpp | 21 +++++++++++-------- test/static_string.cpp | 7 ++++--- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/include/boost/static_string/detail/static_string.hpp b/include/boost/static_string/detail/static_string.hpp index c50ffa7..14b53e9 100644 --- a/include/boost/static_string/detail/static_string.hpp +++ b/include/boost/static_string/detail/static_string.hpp @@ -119,7 +119,7 @@ public: #ifdef BOOST_STATIC_STRING_ALLOW_UNINIT_MEM CharT data_[N + 1]; #else - CharT data_[N + 1]{}; + CharT data_[N + 1]{0}; #endif }; @@ -129,17 +129,17 @@ class static_string_base_zero<0, CharT, Traits> { public: BOOST_STATIC_STRING_CPP11_CONSTEXPR - static_string_base_zero() noexcept { } + static_string_base_zero() noexcept { } BOOST_STATIC_STRING_CPP11_CONSTEXPR static_string_base_zero(std::size_t) noexcept { } - // not possible to constexpr with the static there + // Modifying the null terminator is UB + BOOST_STATIC_STRING_CPP11_CONSTEXPR CharT* data_impl() const noexcept { - static CharT null{}; - return &null; + return const_cast(&null_); } BOOST_STATIC_STRING_CPP11_CONSTEXPR @@ -158,12 +158,15 @@ public: BOOST_STATIC_STRING_CPP14_CONSTEXPR void - term_impl() noexcept - { + term_impl() noexcept { } - } +private: + static constexpr CharT null_{0}; }; +template +constexpr CharT static_string_base_zero<0, CharT, Traits>::null_; + // Optimization for storing the size in the last element template class static_string_base_null @@ -213,7 +216,7 @@ public: #ifdef BOOST_STATIC_STRING_ALLOW_UNINIT_MEM CharT data_[N + 1]; #else - CharT data_[N + 1]{}; + CharT data_[N + 1]{0}; #endif }; diff --git a/test/static_string.cpp b/test/static_string.cpp index ecfbb82..f8b7164 100644 --- a/test/static_string.cpp +++ b/test/static_string.cpp @@ -6971,6 +6971,10 @@ constexpr bool testConstexpr() constexpr auto h = s2.back(); } + static_string<0> a; + + constexpr auto b = a.data(); + //constexpr auto g = s1.assign(1, '1'); //constexpr auto h = s1.assign({'1'}); //constexpr auto i = s1.assign("", 1); @@ -7021,9 +7025,6 @@ runTests() testHash(); - static_string<1>() + static_string<3>(); - static_string<3>() + "ggggg"; - return report_errors(); }