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

Time:02-02

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!

CodePudding user response:

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.

  •  Tags:  
  • Related