www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - function ref param vs pointer param

reply "ref2401" <refactor24 gmail.com> writes:
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);
}
Apr 24 2015
next sibling parent reply "bearophile" <bearophileHUGS yahoo.com> writes:
ref2401:

 void processRef(ref MyStruct ms) {
 	writeln("processRef: ", ms);
 }

 void processPointer(MyStruct* ms) {
 	writeln("processPointer: ", *ms);
ref params don't need the "*" every time you use them inside the function, and don't need the "&" when you call the function. Bye, bearophile
Apr 24 2015
parent reply "ref2401" <refactor24 gmail.com> writes:
processPointer(&ms);
I think doing this way is more descriptive.
Now all readers know that ms might be changed inside the function.
Apr 24 2015
parent "bearophile" <bearophileHUGS yahoo.com> writes:
On Friday, 24 April 2015 at 13:39:35 UTC, ref2401 wrote:
 processPointer(&ms);
 I think doing this way is more descriptive.
 Now all readers know that ms might be changed inside the 
 function.
"ref" at the calling point too. But this idea was refused for D (also because it goes against UFCS chains). Bye, bearophile
Apr 24 2015
prev sibling next sibling parent Steven Schveighoffer <schveiguy yahoo.com> writes:
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
Apr 24 2015
prev sibling parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 04/24/2015 06:23 AM, ref2401 wrote:

 What advantages do ref params give over pointer params?
Another difference is that a ref parameter is not null and what is referred to is not an rvalue. However, it is possible to break that expectation if a pointer is dereferenced and passed to a ref-taking function but then the actual object is gone before the reference is used. Ali
Apr 24 2015
parent "ref2401" <refactor24 gmail.com> writes:
Thank you
Apr 24 2015