Small Buffer Optimization for string and friends

Michel Fortin michel.fortin at michelf.com
Sun Apr 8 08:48:59 PDT 2012


On 2012-04-08 15:06:13 +0000, Andrei Alexandrescu 
<SeeWebsiteForEmail at erdani.org> said:

> On 4/8/12 9:59 AM, Michel Fortin wrote:
>> But as soon as you take a pointer to that string, you break the
>> immutability guaranty:
>> 
>> immutable(char)[] s = "abcd";
>> immutable(char)* p = s.ptr;
>> s = "defg"; // assigns to where?
> 
> Taking .ptr will engender a copy. A small regression will be that 
> address of individual chars cannot be taken.

You know, many people have been wary of hidden memory allocations in 
the past. That's not going to make them happy. I'm not complaining, but 
I think .ptr should return null in those cases. Let people use 
toStringz when they need a C string, and let people deal with the ugly 
details themselves if they're using .ptr to bypass array bound 
checking. Because if someone used .ptr somewhere to bypass bound 
checking and instead he gets a memory allocation at each loop 
iteration… it won't be pretty.

And what about implicit conversions to const(char)[]? That too will 
require a copy, because otherwise it could point to the local stack 
frame where your immutable(char)[] resides. That said, maybe copies of 
small-string optimized immutable(char)[] could be small-string 
optimized const(char)[]. That'd not have any side effect since no one 
can have a mutable pointer/slice to the const copy anyway.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/



More information about the Digitalmars-d mailing list