D1 -> D2

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu Nov 18 13:51:37 PST 2010


On 11/18/10 1:50 PM, Michel Fortin wrote:
> On 2010-11-18 16:02:40 -0500, "Steven Schveighoffer"
> <schveiguy at yahoo.com> said:
>
>> class obj
>> {
>> char[] name;
>> this(char[] name) { this.name = name;}
>> }
>>
>> What to do there? If name is typically a string literal, then string
>> is appropriate. But if there are cases where a name is passed in via a
>> char[] allocated on the heap, then const(char) makes sense. However,
>> you really don't want the name to change at some other point, so if
>> it's not immutable it should idup the name.
>>
>> It's not easy to make this code both safe and efficient. In the end, I
>> think in cases like this I did something like:
>>
>> string name;
>> this(const(char)[] name) { this.name = name.idup;}
>> this(string name) {this.name = name;}
>
> If you're only going to store the string as immutable, I think it's
> better to accept it only as immutable in the constructor. This way you
> pass the responsibility of iduping the string to the caller and this
> might reveal optimization opportunities. For instance:
>
> obj[100] versions;
> foreach (i; 1..100)
> versions[i] = new obj(name.idup);
>
> See how it the inefficiency obvious when the caller is the one calling
> idup?

Yes, I think that's the best idiom (I use it in Phobos in a number of 
places). It's safe and as efficient as it could.

Andrei



More information about the Digitalmars-d mailing list