mutable, const, immutable guidelines

qznc qznc at web.de
Wed Oct 16 23:56:08 PDT 2013


On Wednesday, 16 October 2013 at 20:33:23 UTC, H. S. Teoh wrote:
> I'm of the view that code should only require the minimum of 
> assumptions
> it needs to actually work. If your code can work with mutable 
> types,
> then let it take a mutable (unqualified) type. If your code 
> works
> without modifying input data, then let it take const. Only if 
> your code
> absolutely will not work correctly unless the data is 
> guaranteed to
> never change, ever, by anyone, should it take immutable.

Sounds reasonable. Which one of the following would you prefer?

foo1(const T t) {
   takes_immutable(t.idup);
}

foo2(immutable(T) t) {
   takes_immutable(t);
}

I'd say foo2, which puts the burden of the copy on the caller. 
However, if the caller already has an immutable value an 
unecessary copy is avoided.


More information about the Digitalmars-d-learn mailing list