Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is constexpr of std::wstring().capacity() not equal to std::wstring().capacity()?

I'm not sure if I'm too naïve or simply too unknowing.

But why does the following differ?

constexpr auto nInitialCapacity1 = std::wstring().capacity();
const auto     nInitialCapacity2 = std::wstring().capacity();

In Visual Studio 2022/17.0.5 the code above results in:

nInitialCapacity1 = 8
nInitialCapacity2 = 7

Why is the result of the constexpr (compile time) version not equal to the const version of the call?

Thanks for any explanation!

like image 513
Martin Lemburg Avatar asked Feb 22 '26 19:02

Martin Lemburg


1 Answers

Microsoft's STL disables short string optimisation in constant evaluated contexts, so it allocates memory instead.

The allocations are always one more than a power of two, so the capacity (which excludes the last L'\0') is always a power of two.

In the non-constant-evaluated version, the short string buffer can hold 8 characters, one of which is a L'\0', so the capacity is 7.

like image 161
Artyer Avatar answered Feb 24 '26 09:02

Artyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!