function ref param vs pointer param

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 24 06:58:41 PDT 2015


On 4/24/15 9:23 AM, ref2401 wrote:
> What advantages do ref params give over pointer params?
>
> struct MyStruct {
>      string str;
>
>      this(string str) { this.str = str; }
> }
>
> void processRef(ref MyStruct ms) {
>      writeln("processRef: ", ms);
> }
>
> void processPointer(MyStruct* ms) {
>      writeln("processPointer: ", *ms);
> }
>
> void main(string[] args) {
>      auto ms = MyStruct("the ultimate answer to everythin is the number
> 42");
>
>      processRef(ms);
>      processPointer(&ms);
> }

A ref param is somewhat safer, because you cannot do pointer arithmetic 
on it. A ref will ALWAYS point at the same memory location, because it 
cannot be rebound.

The compiler can also take advantage of the characteristics of ref, as 
it does with the -dip25 switch.

-Steve


More information about the Digitalmars-d-learn mailing list