Christopher Wright wrote:
Lionello Lunesu wrote:

"Christopher Wright" <dhase...@gmail.com> wrote in message news:gugs7b$70...@digitalmars.com...
Lionello Lunesu wrote:
I like shared/const/immutable as much as the next guy, but there are now 2x2x3=12 ways to decorate a variable. Furthermore, by either declaring the variable globally or locally (stack), we end up with 24 possible declaration. See the code at the end of this post.

The decision to make a variable a static class or module member is independent of whether to make it shared or not.

You're right, of course. I realize now that "static" is a storage class (when used locally) not a type modifier.

Shared and const-level have to do with controlling access to the variable.

An immutable variable does not need to be declared shared.

So, immutable implies shared.

Immutable is threadsafe. Shared implies automatic locking, I believe; immutable variables do not need any locking.

So one has to wonder what code will be generated for "shared immutable".. an immutable with (useless) locking?

Shared const is for publish-subscribe sort of deals.

You mean one thread can change the value, but for another thread it's constant? I can see how it would be useful using reference types, but I don't understand how it would work with value types..

Shared const doesn't really work for value types; it ends up being the same as immutable. Unless you have a mutable pointer to the value, in which case you can write to the value through that pointer. That is not safe -- the compiler is free to see that this variable is const and a value type, which means you can't ever write to it, and then put it in read-only memory.

Const that doesn't boil down to immutable works a fair bit better with object-oriented code. You wrap your value in a class, create a mutable instance, and send it to a bunch of other functions or objects or threads expecting a const object. They can't use the mutators, but they can use the accessors.

Got it. Thanks..

L.

Reply via email to