Object as function argument
Chris Sperandio via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Mar 5 11:58:15 PST 2015
Below the code:
module item;
import std.stdio;
class Item
{
ulong count;
static void call1(Item item)
{
writeln("(call1) Addr: ", &item);
}
static void call2(ref Item item)
{
writeln("(call2) Addr: ", &item);
}
static Item call3(Item item)
{
writeln("(call3) Addr: ", &item);
return item;
}
static Item call4(Item item)
{
// Here, I change the count
item.count = 100;
return item;
}
}
void main()
{
auto item = new Item();
writeln("(main) Addr item=", &item);
Item.call1(item);
Item.call2(item);
auto res3 = Item.call3(item);
writeln("(main) res3 item=", &res3);
auto res4 = Item.call4(item);
writeln("(main) res4 item=", &res4);
assert(item.count == 100);
}
I get:
(main) Addr item=7FFF5D797818
(call1) Addr: 7FFF5D7977F8
(call2) Addr: 7FFF5D797818
(call3) Addr: 7FFF5D7977F8
(main) res3 item=7FFF5D797820
(main) res4 item=7FFF5D797828
On Thursday, 5 March 2015 at 19:48:38 UTC, w0rp wrote:
> On Thursday, 5 March 2015 at 19:35:35 UTC, Chris Sperandio
> 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 :) ?
>>
>> Chris
>
> If you share your code, I'll be happy to take a look. Classes
> are reference types, so passing T for a class should pass the
> reference to the object.
More information about the Digitalmars-d-learn
mailing list