2
votes

I am currently learning D, and see that it allows one to define pointers in much the same way as in C++, however, it also allows pass by reference via the ref keyword. With regards to function parameters, I have the following questions:

  1. Is it possible to define function paremeters in D entirely without using pointers? If so, what are the best practices for doing so, in general? My understanding is that the purpose of the ref keyword is to do away with having to define function input parameters as pointers.

  2. Are there any cases where using pointers rather than the "ref" keyword in functions is significantly more advantageous even if the answer to question 1 is "yes"?

For example, the following two codes produce identical results. Is one better than the other, besides it being more convenient to use the "ref" keyword?

Code 1 (Uses pointers):

import std.stdio;

struct X {
    int s;
    int y;
}

pure void my_func(X *x) {
    x.s = 10;
    x.y = 90;
}

void main() {
   X cat = X(1,2);
   X *cat_ptr = &cat;
   writeln(cat.y);
   my_func(cat_ptr);
   writeln(cat.y);
}

Code 2 (Uses "ref" keyword):

import std.stdio;

struct X {
    int s;
    int y;
}

pure void my_func(ref X x) {
    x.s = 10;
    x.y = 90;
}

void main() {
   X cat = X(1,2);
   writeln(cat.y);
   my_func(cat);
   writeln(cat.y);
}

I mostly come from a Java background, so my understanding of these concepts is not great.

1

1 Answers

2
votes

I find it's rare to see a raw pointer in D. For arrays you use slices (like int[]). To pass something by reference, you declare it as a ref parameter. You use classes where they fit, and there's RefCounted, which is essentially a smart pointer.

Probably the most common replacement of pointers in D are slices (and a pointer can in many ways be considered a slice that contains either zero or one element). That is, if you don't consider this, which also essentially is a pointer.

D's slices are just thin wrappers around pointers, so you can basically do the exact same things with them, but the common operations are safer with slices. The trade-off is it's very slightly slower, since element access is range-checked.

Since you say you come from a Java background, I'll add you can generally write almost the exact same code in D, and it will compile and run, and do the exact same thing it did in Java. It won't be idiomatic D, but it will work.

Update, since question changed:

In the example code, there's no reason to use pointers over ref parameters - it should compile to the exact same machine code. Generally, the only time you should use pointers is when you're going to do pointer arithmetic. If you're not sure you're going to, just assume you won't.