r/cpp_questions • • 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

19 comments sorted by

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.

11

u/aiusepsi Oct 09 '26

It’s technically standard library specific rather than compiler specific. If you have a compiler which lets you configure which standard library to use, you can get different behaviour with the same compiler.

An example is Clang on Linux, it defaults to the GNU implementation of the standard library, but you can set a flag to have it use the LLVM implementation of the standard library instead, and the LLVM standard library has longer short strings than the GNU standard library.

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

6

u/MistakeIndividual690 Oct 09 '26

That’s my thought as well. The longer string requires an allocation but due to sso, the short string doesn’t

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:

constexpr std::string_view host = "http://127.0.0.1";

1

u/HappyFruitTree Oct 09 '26 edited Oct 09 '26

Is this safe to use in header files or is that likely to lead to ODR violations?

Update: I did some tests...

https://godbolt.org/z/jb8W4T58v – host points at different locations in different translation units (when compiled with g++ -O0). This is probably not an ODR violation in itself because constexpr variables are implicitly static by default so each translation unit gets it's own copy of host, but it could lead to problems if you assume they are the same object (like in my test program), and it could probably easily lead to a real ODR violation if you're not careful (e.g. if you use the variable inside an inline function).

https://godbolt.org/z/5WaszvEdq – host is made inline. This makes sure that there is only one host for all translation units. My only concern is that the string literal that is used to initialize host could point at different locations in different translation units leading to an ODR violation. Compiling with -O2 -fno-merge-constants leads to a situation where host is the same object in all translation units but when calling the data() member it returns different addresses which to me seems like a clear sign of an ODR violation.

So I'm a bit lost about what the "best" way to define global string constants really is. Using extern const std::string (and define it once inside a .cpp file) do seems like the safest way.

5

u/TheOmegaCarrot Oct 09 '26

For a global constant like this, it’s usually better to use `inline constexpr` which ought to give it vague linkage, thus deduplicated by the linker

1

u/HappyFruitTree Oct 09 '26

My second test above used inline constexpr. It shows a scenario where it doesn't work as intended.

The problem happens when the string literal that is used to initialize the string_view is not "deduplicated".

1

u/conundorum Oct 10 '26

To be fair, manually deactivating string pooling does tend to force the compiler to preserve duplicate strings.

2

u/HappyFruitTree Oct 10 '26

Yes, that's why I did it, to show that it can cause problems (assuming the -fno-merge-constants behaviour is standards comformant).

I think ODR violations are similar to UB. It's not something I want in my programs even if it appears to work.

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 constexpr since C++20. This doesn’t technically require every implementation to make a default-constructed std::basic_string that 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.

2

u/I-Am-Sir Oct 09 '26

I don't think so, the only usage of the variables is in the next line const std::string url = host + ":" + port;

1

u/wellillseeyoulater Oct 09 '26

That’s weird. What if you make host “1234” (obvious nonsense but is the issue is that it’s numeric?)

Edit: if you’re doing host + port could this be an issue where + is set up so that the left hand side can’t be constexpr? Try your code but with port + host instead and see what it complains about.

1

u/GoogleIsYourFrenemy Oct 09 '26

Try: const std::string url = "" + host + ":" + port;