[RFC] std::string(0);

Daniel Frey daniel.frey@aixigo.de
Fri Jun 11 16:38:00 GMT 2004


Jonathan Wakely wrote:
> On Fri, Jun 11, 2004 at 02:50:36PM +0200, Daniel Frey wrote:
> 
>>I would like to suggest a small improvement to basic_string. As the 
>>subject already says, it's about std::string(0);
>>
>>Obviously, it's illegal to pass a const char* to the ctor of 
>>basic_string that is zero. The current implementation results in a SEGV. 
>>I would like to catch *some* of the cases at compile-time instead of 
>>having a crashing program. :)
> 
> The merits of this idea aside, using 3.4 I get:
> 
> terminate called after throwing an instance of 'std::logic_error'
>   what():  basic_string::_S_construct NULL not valid
> Abort trap (core dumped)

Better than before, but still run-time instead of compile-time. As far 
as I'm concerned, I always prefer catching errors at compile-time over 
catching them at run-time, however stupid the compile-time diagnostic 
looks. I hope everyone agrees to that :)

> Your idea would mean that std::string(1) results in an access error,
> rather than an error about converting int to const char* - I don't know
> how much that would matter, since it fails to compile either way, but I
> can see an argument that the required diagnostic isn't given.
> 
> Would there be any issues for implicit conversions?  e.g.
> 
> struct MyStupidAllocator
> {
>     MyStupidAllocator(int) {}
>     // ...
> };
> 
> std::basic_string<char, std::char_traits<char>, MyStupidAllocator> s(1);
> 
> Wouldn't this change from a foolish, but legal program to an illegal one?

Indeed, good catch! It seem we need two lines in the private section of 
basic_string to work around this:

template<...> class basic_string
{

private:
   class LiteralZeroProtector;
   basic_string( const LiteralZeroProtector* );

   ...
};

This would ambiguate calls with a literal zero, and as an added bonus, 
it would result in even better diagnostics than my original suggestion.

Regards, Daniel

-- 
Daniel Frey

aixigo AG - financial solutions & technology
Schloß-Rahe-Straße 15, 52072 Aachen, Germany
fon: +49 (0)241 936737-42, fax: +49 (0)241 936737-99
eMail: daniel.frey@aixigo.de, web: http://www.aixigo.de




More information about the Libstdc++ mailing list