Why not delay the detection of the length to the first call of strlen?

 

What it should do:

-> Confirm the underlying buffer contains at least one NUL byte, if possible to be confirmed: This is done by the constructors.

-> Avoid repeated traversals for strlen: Cache the length.

-> Don't calculate the length, if not needed. Only do it at first use. Should be as efficient as a char* pointer (at least regarding the operations).

 

The confirmation of NUL is not always possible or needs different pre-conditions or different effort:

 - constructing from char*: We don't know the length of the buffer. Confirmation not possible.

 - constructing from char*+size of buffer: Can be done in O(n)

 - constructing from types with guaranteed NUL at the end, but possible intermediate NUL bytes: Already confirmed by type.


Computing the size on demand (and then caching it) means that size() is either not const, or that the type has at least one mutable member, which does prevent certain use cases like putting it into a constexpr variable IIRC. Either way, this sounds unattractive.