Using in as a parameter qualifier

Ali Çehreli acehreli at yahoo.com
Thu May 30 23:42:41 PDT 2013


On 05/30/2013 10:36 PM, Shriramana Sharma wrote:

 > struct pair {

It is more common to start type names with a capital letter: Pair.

 >    double x,y ;
 >    this () {}

That is not allowed. In D, every type has the .init property, which is 
its default value.

 >    this (double x, double y) { this.x = x ; this.y = y ; }
 > }

That is sensible to ensure that both values are provided. Otherwise, the 
following struct definition is sufficient:

struct Pair {
   double x, y;
}

void main()
{
     auto p0 = Pair();
     auto p1 = Pair(1.5);        // only p1.y is 0
     auto p2 = Pair(2.5, 3.5);
}

You can also set the .init value of the whole type:

struct Pair {
     double x = 10.75;
     double y = 20.25;
}

 > Consider a function that operates on a pair:
 >
 > double abs2 ( pair a ) { return a.x * a.x + a.y * a.y ; }
 >
 > In C++ the function signature would be: double abs2 ( const pair & a )
 >
 > So I thought const ref pair a would be appropriate in D -- is that right?

Yes:

double abs2(ref const(Pair) a) { /* ... */ }

 > How about the "in" qualifier? Does it only replace C++'s const in this
 > case or does it also guarantee that the object will not be copied
 > (&/ref) ?

'in' is nothing but 'scope const' (scope is not implemented yet):

double abs2(in Pair a) { /* ... */ }

Of course, pass-by-vale (the other C++ option) is also possible:

double abs2(Pair a) { /* ... */ }

This one has the added benefit of compiler's automatic moving of the 
value to the function. You know that 'a' is a copy of the argument so 
you can safely move it for use later.

 > Also: does D not require member initializer lists like in C++? In C++
 > I would write the this(double,double) above as: pair(double x, double
 > y):x(x),y(y){} -- since that language is supposed to guarantee that
 > once we enter the { of the constructor, all sub-objects are
 > initialized.

D guarantees that every member is already initialized by their .init 
value when the constructor is entered (unless the initial value is 
'void'). There are optimizations opportunities through flow analysis but 
the compiler does not apply them yet.

Ali



More information about the Digitalmars-d-learn mailing list