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);
    }

Reply via email to