D1 -> D2

Michel Fortin michel.fortin at michelf.com
Thu Nov 18 13:50:41 PST 2010


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?

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



More information about the Digitalmars-d mailing list