mutable, const, immutable guidelines
qznc
qznc at web.de
Wed Oct 9 16:52:58 PDT 2013
On Wednesday, 9 October 2013 at 15:50:55 UTC, Daniel Davidson
wrote:
>> > I would rephrase the second guideline as: "Never dup or idup
>> an argument
>> > to make it mutable or immutable, but require the caller to do
>> this
>> > (might be able to avoid it)".
>>
>> Agreed. But it means you agree with me that immutable should
>> indeed appear on function signatures as needed.
>
> I don't really agree. Naturally, if const were used all the way
> down there would be no need for copies. It is the introduction
> of immutable (via string in your example) that breaks the rule
> and causes the pain. But then if the rule were adopted globally
> - immutable is never used on parameters in a signature, only
> const is used, when would you start seeing any benefit to the
> immutable keyword?
The benefit of immutable is that nobody else can change it.
Functions that would be non-thread-safe with const arguments are
thread-safe with immutable arguments.
That relationship with thread-safety almost seems to be a good
guideline.
5. If a function is not thread-safe due to const arguments,
consider making it immutable. Otherwise you must explicitly
document the lack of thread-safety.
>> > For more guidelines:
>> >
>> > 3. Return value, which are freshly created, should never be
>> const. They
>> > should be mutable or immutable.
>>
>> Agreed. I say that it should be mutable if the function is
>> pure, as such a return values is automatically convertible to
>> immutable.
>>
>> > Basically, I cannot come up with a case, where const would be
>> preferable
>> > to mutable and immutable. Maybe someone is able to find a
>> good example?
>>
>
> I don't know if these are good examples, but they are examples:
>
> From zip.d:
> const(void)[] compress(const(void)[] buf)
Looking it up (in zlib.d actually) it could just as well return
an immutable array, since it is freshly allocated.
> From vibe:
> const(Json) opIndex(string key) const {
Not sure where exactly this comes from. Seems to be some kind of
map? In this case the value is not "freshly created", so the
guideline does not apply.
> I'm confused by the term "usable as mutable, const, immutable"?
> Isn't it true that types are not mutable, const, immutable in
> their definition but only in their context?
MyInt is a type, probably mutable.
immutable(MyInt) is also a type, but immutable.
const(MyInt) is also a type, but const.
These are example of immutable and const being used as type
constructors. They create a new type from an existing one (MyInt).
More information about the Digitalmars-d-learn
mailing list