Preventing writes to a global struct instance with const?

Bradley Smith digitalmars-com at baysmith.com
Wed Jan 31 15:33:24 PST 2007


Rick Mann wrote:
> I have an external variable declared like this:
> 
> struct
> ControlID
> {
> 	uint			signature;
> 	int				id;
> };
> extern extern (C) const HIViewID kHIViewWindowContentID;
> 
> But when I am able to write code like this without complaint from the compiler (GDC 0.21/DMD 1.00):
> 
> kHIViewWindowContentID.signature = 123;
> 
> I'd like to prevent that. Is such a thing possible?
> 

Why doesn't private protection work on structs? I tested it with DMD 
1.003 and was surprised by the result.

struct ControlID {
   private uint signature_;
   private int id_;
	
   uint signature() {
     return signature_;
   }
}

void main() {
   ControlID id;
   id.signature = 123;  // Compiler error
   uint i = id.signature;

   id.signature_ = 123;  // Doesn't fail. Should it?
}


More information about the Digitalmars-d-learn mailing list