Boost logo

Boost :

Subject: Re: [boost] [string_ref] string literal constructor
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2013-11-06 18:54:17

On 7/11/2013 05:19, Quoth Marshall Clow:
> On Nov 2, 2013, at 10:49 PM, Antony Polukhin <antoshkka_at_[hidden]> wrote:
>> template< std::size_t N >
>> basic_string_ref( const charT( &str )[N] )
>> : basic_string_ref( str, std::min(N, strlen(str)) ) /* pseudo code,
>> we'll need something like strlen_s */
>> {}
>> Such constructor won't change the current behavior
>> string_ref ( "test\0test" ) // { ptr, 4 }
>> but will also work for non-zero terminated fixed length arrays:
>> const char s[] = {'0', '1', '2'};
>> string_ref test(s); // {ptr, 3}
> No, actually, it won't, because the strlen will read past the end of
> the array, looking for the terminating NULL. (and that's undefined
> behavior)

I was thinking about pointing that out earlier but I assumed that
resolving that issue was what he meant by the "strlen_s" comment.
Although given a strlen_s that eliminates that possibility, the call to
std::min would be redundant, so either way it's a little odd.

(Though most of the time you'd be able to get away with the above even
as written, because the chances that you'd run off the top of the stack
before encountering a null byte are almost nil. Not that it should be
encouraged, of course.)

> Personally, I'm content with the current situation where
> * If you have a NULL terminated string (by far the most common
> case),the { pointer } constructor works fine.
> * If you have something else, you have to use the { pointer, size }
> constructor.

While I mostly agree with this, it is probably just as common to have a
char buffer on the stack that you *think* is null terminated, but might
not be. (Particularly if the classic "strncpy" has been involved at
some point.) That's where having this sort of constructor could be
beneficial, to act as a backstop against such issues.

Though personally I'm still inclined to leave it explicitly up to the
application -- the app code needs to be much more aware of what it's
doing if it's intentionally passing around (potentially) non-terminated
strings; and if it's accidental then it's a bug that should be fixed
immediately (eg. with a safe_strncpy) rather than being quietly resolved
by a library.

Boost list run by bdawes at, gregod at, cpdaniel at, john at