Calls to struct methods and immutable
    bearophile 
    bearophileHUGS at lycos.com
       
    Thu Nov 15 06:06:56 PST 2012
    
    
  
Joseph Rushton Wakeling:
>       auto foo = cast(immutable) Foo(3, 4);
Strive to write D code as much cast-free as possible, because
they are dangerous.
> The reason seems pretty evident -- making the instance 
> immutable means that the temporary internal variable c in 
> check() can't be (over)written.
You are wrong. A version of your code:
import std.math;
struct Foo {
      int a, b;
/*
      this(int a, int b) {
          this.a = a;
          this.b = b;
      }
*/
      void check() const pure nothrow {
          immutable real p = a ^^ 2 + b ^^ 2;
          assert(sqrt(p) < 10);
      }
}
void main() {
      auto foo = immutable(Foo)(3, 4);
      // immutable foo = Foo(3, 4); // simpler alternative
      foo.check();
}
Bye,
bearophile
    
    
More information about the Digitalmars-d-learn
mailing list