On Sunday, 16 August 2015 at 22:35:15 UTC, Alex Parrill wrote:
On Sunday, 16 August 2015 at 22:31:02 UTC, Brandon Ragland
wrote:
Hi All, I'm a bit confused as to how Classes in D are passed
in arguments and returns.
Take this for example:
class MyClass{
int x = 2;
}
And then in app.d
ref MyClass doStuff(){
MyClass mc = new MyClass() // Heap allocation, using new....
return mc;
}
The above fails, as "escaping reference to local variable"
however, this was created using new.... Not understanding what
the deal is, this should be a valid heap allocated object, and
therefore, why can I not pass this by reference? I don't want
this to be a local variable...
So this begs the question: Are Classes (Objects) passed by
reference already?
-Brandon
Classes are reference types, a la Java/C#.
class MyClass {
int x = 5;
}
void main() {
auto c1 = new MyClass();
auto c2 = c1;
c1.x = 123;
assert(c2.x == 123);
}
Thanks,
That makes more sense. Though it does make the ref method
signature unclear, as it only applies to literals at this point?
Would you still need the ref signature for method parameters for
classes to avoid a copy? Such that I could work on the class
itself, and not a copy.
//This is reference?
void doStuff(ref MyClass mc){
return;
}
or would this also be a valid reference type:
//This is a copy?
void doStuff(MyClass mc){
return;
}