www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - ACLs for variables - lock / unlock idea

reply Cecil Ward <d cecilward.com> writes:
An idea, I’d be interested to hear if this might be at all useful 
to anyone -

If and only if a variable is declared as modifiable (neither 
immutable nor const), would it possibly be useful to be able to 
have a kind of scope const on/off switch to either impose const 
within a block, and/or the converse, that is to impose const as 
the default everywhere starting say from an initial directive 
straight after the (modifiable) declaration, while being able to 
flick the const protection switch off within a block?
Sep 29
parent reply Atila Neves <atila.neves gmail.com> writes:
On Friday, 29 September 2017 at 11:12:32 UTC, Cecil Ward wrote:
 An idea, I’d be interested to hear if this might be at all 
 useful to anyone -

 If and only if a variable is declared as modifiable (neither 
 immutable nor const), would it possibly be useful to be able to 
 have a kind of scope const on/off switch to either impose const 
 within a block, and/or the converse, that is to impose const as 
 the default everywhere starting say from an initial directive 
 straight after the (modifiable) declaration, while being able 
 to flick the const protection switch off within a block?
auto modifiable = foo(); { const nonModifiable = modifiable; //... } Or refactor the scope into a function accepting your modifiable variable as const. Atila
Sep 29
parent Cecil Ward <d cecilward.com> writes:
On Friday, 29 September 2017 at 13:07:32 UTC, Atila Neves wrote:
 auto modifiable = foo();
 {
     const nonModifiable = modifiable;
     //...
 }
I had already thought about using two names. I don’t think that using a kind of ‘const-alias’ mechanism (or ‘const reference’, in the C++ var& sense) would be a good idea at all. By this I mean something where a modifiable variable has two names, only of of them permitting write access. The reason why this wouldn’t be good enough is that there would be nothing much stopping me from forgetting what I’m doing and going back to using the wrong name at some point, without any warnings. Slight mitigation would be if the original declaration was something like myvar_writeable and the const alias for it was called simply myvar, so that the default brain-free form would be the safe one and you would have to go out of your way to get write access. It still wouldn’t be that strong though. Iirc you get told off if you block access to variables by using ‘shadowing’, declaring an exactly matching name using an alias declaration in a normal basic block scope. (I suspect you can do so inside function bodies, I don’t think d moans about you blocking access to matching variables that are in global or outer, non-global, non-local scopes if you write ‘shadowing’ local variable declarations - not sure.) Anyway, couldn’t use that either and it’s no way usable enough for me.
Sep 29