|
Boost : |
Subject: Re: [boost] [string_ref] string literal constructor
From: Marshall Clow (mclow.lists_at_[hidden])
Date: 2013-11-06 11:19:02
On Nov 2, 2013, at 10:49 PM, Antony Polukhin <antoshkka_at_[hidden]> wrote:
> 2013/11/3 Michael Marcin <mike.marcin_at_[hidden]>
>
>> On 11/2/2013 9:43 AM, Marshall Clow wrote:
>>
>>> On Nov 1, 2013, at 4:42 PM, Michael Marcin <mike.marcin_at_[hidden]> wrote:
>>>
>>> I noticed string_ref doesn't have a constructor for a string literal.
>>>> Wouldn't this save a call to strlen for a common case?
>>>>
>>>> Ex.
>>>>
>>>> template< std::size_t N >
>>>> basic_string_ref( const charT( &str )[N] )
>>>> : basic_string_ref( str, N-1 )
>>>> {
>>>> static_assert(N >= 1, "not a string literal");
>>>> }
>>>>
>>>> string_ref test( "test" );
>>>>
>>>
>>> So, what should
>>> string_ref ( "test\0test" )
>>> do?
>>>
>>> { ptr, 4 } --> current behavior
>>> { ptr, 9 } --> your suggested behavior
>>>
>>>
>> So, what should
>>
>> const char s[] = {'0', '1', '2'};
>> string_ref test{s};
>>
>> do?
>>
>> Neither seems to be very important and can be handled by requiring sane
>> preconditions.
>
>
> Marshall, how about adding the following constructor:
>
> 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)
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.
-- Marshall
Marshall Clow Idio Software <mailto:mclow.lists_at_[hidden]>
A.D. 1517: Martin Luther nails his 95 Theses to the church door and is promptly moderated down to (-1, Flamebait).
-- Yu Suzuki
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk