Pointer to Object Questions
Kirk McDonald
kirklin.mcdonald at gmail.com
Sat Dec 30 16:55:35 PST 2006
Thomas Kuehne wrote:
> Kirk McDonald schrieb am 2006-12-30:
>
> <snip>
>
>> Since classes are by reference, anyway, there's no good reason to throw
>> around pointers to objects.
>
> There is at least one valid use case for pointers to objects:
>
> #
> # ClassType[IndexType] aa;
> # //...
> # ClassType* c = index in aa;
> #
>
> Thomas
>
But what you have there isn't a pointer to an object, it's a pointer to
a reference. This is an important distinction.
import std.stdio;
class Foo{}
void main() {
Foo f = new Foo;
void* ptr = cast(void*)f;
Foo* fptr = &f;
writefln("ptr: %s", ptr);
writefln("fptr: %s", fptr);
writefln("*fptr: %s", *cast(void**)fptr);
}
$ ./test
ptr: B7CBAFE0
fptr: BF96E110
*fptr: B7CBAFE0
In this example, ptr is a pointer to the actual object. fptr is a
pointer to the /reference/. Because variables of type 'Foo' are actually
pointers, variables of type Foo* are pointers to pointers.
The following, therefore, is a very bad idea:
Foo* func() {
Foo f = new Foo;
return &f;
}
This returns a pointer to a stack variable (the Foo reference f). This
is a bad idea for the same reason returning a pointer to any stack
variable is a bad idea.
--
Kirk McDonald
Pyd: Wrapping Python with D
http://pyd.dsource.org
More information about the Digitalmars-d-learn
mailing list