Object as function argument
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Mar 5 11:59:25 PST 2015
On Thursday, March 05, 2015 19:35:34 Chris Sperandio via Digitalmars-d-learn wrote:
> Hi,
>
> I'm a developer coming from C and I've a question about class
> instance as method or function parameter.
> In the book "The D Programming Language", I read the instance was
> passed by reference to functions (in the opposite of structures).
> I understood that it was the same object in the function and the
> caller. But I'm think, I was wrong because when I print the
> addresses of an object before the function call and inside the
> function, they're not the same but the changes from the function
> are kept in the instance.
> If I use the "ref" qualifier in the function declaration, the 2
> addresses are the same.
>
> How do the changes work in the function? Is there a copy ? Or a
> "magic" trick :) ?
MyClass c;
is a reference to an object. So, if you do &c, you're taking the address of
the reference, not the object. So, it's like if you had
MyClass* c;
in C/C++ and you did &c. So, if you have
void bar()
{
auto c1 = new MyClass;
foo(c1);
}
void foo(MyClass c2)
{
}
then c1 and c2 have different addresses just like if they would if they were
explictly pointers. Changing foo to
void foo(ref MyClass c2)
{
}
means that you're passing the reference itself by ref, making it essentially
equivalent to
void foo(MyClass*& c2)
{
}
in C++. So, c2's address is going to be the same as c1, because they're
essentially the same reference/pointer at that point. If you want the
address of the object itself rather than its reference, then you need to
cast it to void*. e.g. this code will print the same value for c1 and c2:
import std.stdio;
class MyClass {}
void main()
{
auto c1 = new MyClass;
writeln(cast(void*)c1);
foo(c1);
}
void foo(MyClass c2)
{
writeln(cast(void*)c2);
}
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list