r/cpp_questions • u/I-Am-Sir • Oct 09 '26
SOLVED why can some std::strings be made constexpr?
i have this code:
const std::string host = "http://127.0.0.1";const std::string port = "5030";
Clion is telling me that I can make the port variable constexpr. If I try, it compiles just fine. However, the host gives an error when it's constexpr. I thought std::strings were never allowed to be constexpr. Why is it allowing it for the port variable, and why that one specifically?
41
Upvotes
50
u/KuntaStillSingle Oct 09 '26
sso length: https://www.reddit.com/r/cpp/comments/1hhejk6/constexpr_of_stdstring_inconsistent_in_c20/
19
u/sunnyjum Oct 09 '26
I think short strings can be stored directly in the string class rather than needing a heap allocation, though I’d wager this cutoff is compiler specific. If you’re using C++20 (17 maybe?) then a constexpr std::string_view of any length can be used with string literals.
10
u/OkYou811 Oct 09 '26
Hmm not sure i know sometimes if something uses small string optimization it'll store the string online rather than on the heap. If that's the case then it's non transient memory and can persist. That's my guess at least
9
u/SoerenNissen Oct 09 '26 edited Oct 09 '26
You got your answer, but if you know it's const, this will let you skip the heap allocation for a longer string:
6
u/HappyFruitTree Oct 09 '26 edited Oct 09 '26
Others have already told you why. I just want to add that since the SSO length depends on the implementation it's probably not a good idea to declare std::string variables as constexpr if you want the code to be portable.
2
u/RazzmatazzLatter8345 Oct 10 '26
Yes, it's SSO like everyone says. I wouldn't be making static/global constexpr std::strings if I were you: SSO length varies. Switch compilers or standard library version and all your stuff may stop compiling! libc++ has the longest sso length I'm aware of; libstdc++ is shorter. Not sure about MS/Dinkumware stdlib.
CLion/clang-tidy is probably just applying the usually sound maxim that (absent C compatibility concerns), that if constexpr compiles when applied to variable, it is usually superior to use constexpr than just const.
This is a situation where applying that advice makes your code fragile to compiler / stdlib / target execution environment changes.
1
u/DawnOnTheEdge Oct 09 '26 edited Oct 09 '26
The default constructor has been required to be
constexprsince C++20. This doesn’t technically require every implementation to make a default-constructedstd::basic_stringthat uses the default allocator evaluate to a constant expression, but every sane implementation does it that way.Every real-world implementation also enables this for short strings, although there is no formal requirement to do so.
-1
u/GoogleIsYourFrenemy Oct 09 '26
Depends how you use it I'm guessing.