xxxInPlace or xxxCopy?

Jonathan M Davis jmdavisProg at
Wed Jan 19 16:53:44 PST 2011

On Wednesday, January 19, 2011 15:33:16 Andrei Alexandrescu wrote:
> I'm consolidating some routines from std.string into std.array. They are
> specialized for operating on arrays, and include the likes of insert,
> remove, replace.
> One question is whether operations should be performed in place or on a
> copy. For example:
> string s = "Mary has a lil lamb.";
> // Implicit copy
> auto s1 = replace(s, "lil", "li'l");
> assert(s == "Mary has a lil lamb.");
> // Explicit in-place
> replaceInPlace(s, "lil", "li'l");
> assert(s == "Mary has a li'l lamb.");


> So that would make copying the default behavior. Alternatively, we could
> make in-place the default behavior and ask for the Copy suffix:
> string s = "Mary has a lil lamb.";
> // Explicit copy
> auto s1 = replaceCopy(s, "lil", "li'l");
> assert(s == "Mary has a lil lamb.");
> // Implicit in-place
> replace(s, "lil", "li'l");
> assert(s == "Mary has a li'l lamb.");


> Thoughts?

Haven't we been using the approach that string operations generally make copies 
(in many cases slices) and marking functions that do it in place with InPlace? 
That's certainly the approach that I'd prefer. And considering that strings 
(which would be the most common use of arrays, I would think) have immutable 
elements and generally _can't_ do anything in place, that would imply that 
copying/slicing would be the default rather than doing operations in place.

Also, if you're looking to minimize code breakage, you're going to have to go 
with using copy by default and in place for functions marked for it, because the 
existing versions of functions like replace have been making copies. So, 
switching to in place by default would break more code.

Being forced to use functions with copy in the name would make dealing with 
strings more annoying, since they would _have_ to be using the copy versions, 
and it would be the versions with copy in the name which would be used the most, 
which seems really backwards.

So, I really think that copying should be the default and in place functions 
should be marked with InPlace. It's more consistent with current behavior and 
would generally result in less typing.

- Jonathan M Davis

More information about the Digitalmars-d mailing list