Unique vs. shared return values

Ali Çehreli acehreli at yahoo.com
Thu Feb 2 15:23:13 PST 2012

strings provide opportunities for optimization. For example, 
std.string.leftJustify() returns

- either a slice of the entire input string when the field is shorter 
than the string (this is an optimization)

- or a new string when the field is larger than the string

The following program demonstrates this behavior:

import std.string;
import std.array;

void main()
         dchar[] input;
         input ~= "hello";

         auto result = leftJustify(input, 3);
         result.front = 'X';
         assert(input.front == 'X');    // <-- input is modified

         dchar[] input;
         input ~= "hello";

         auto result = leftJustify(input, 6);  // note: now 6, not 3
         result.front = 'X';
         assert(input.front == 'h');    // <-- input is NOT modified

The issue is whether the caller can be sure about the uniqueness of the 
returned data. Of course the behavior can be documented and the user can 
check the length before calling:

     auto result = (s.length > width) ? s.dup : leftJustify(s, width);

Now the user knows that 'result' is always a copy.

[A side question is whether leftJustify() should throw when the field 
width is shorter than the string. I wouldn't object that behavior. 
Exceptions are great: they remove difficult questions. :)]

Of course this is not a criticism of leftJustify(). I face such 
decisions frequently myself. I am curious about what you think about 
functions that *may* return unique data.

Is that a problem for you? Have you developed guidelines to deal with it?

Thank you,

More information about the Digitalmars-d mailing list