Newbie question: Return a locally allocated variable

Adam D. Ruppe destructionator at gmail.com
Mon Sep 14 16:44:14 UTC 2020


On Monday, 14 September 2020 at 16:29:11 UTC, Fitz wrote:
> I expect the following code below to create 10 items with 10 
> different addresses, instead they all have the same address?

You are taking the address of the local variable holding 
reference, not the reference itself.

> class Bob {
> }
>
> Bob *bobFactory() {
>     Bob bob = new Bob;
>     Bob *pBob = &bob;
>
>     return pBob;
> }

This is a common mistake with people coming from C++. A D class 
is more like a Java class - it is automatically a reference.

So your class Bob here in D would actually be represented as 
`Bob*` in C++.

Thus when you define `Bob*` in D, that's like a `Bob**` in C++... 
a pointer to a pointer. Thus you're getting the address on the 
stack of the local, not at all what you want.

Your factory should really just be:

Bob bobFactory() { return new Bob; }

Then to compare addresses, do:

writeln(cast(void*) bob); // convert the reference itself to a 
pointer


More information about the Digitalmars-d-learn mailing list