Does D provide automatic dereferencing for accessing members through pointers?

Gary Willoughby via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 27 12:25:41 PDT 2014


This is something that has been on my mind since i discovered 
this the other day. Does D provide automatic dereferencing for 
accessing members through pointers?

Here's an example:

import core.stdc.stdlib : malloc, free;

struct Foo
{
	public int bar;
}

void main(string[] args)
{
	auto foo = cast(Foo*)malloc(Foo.sizeof);

	foo.bar = 42;

	// Dereference the struct before accessing members.
	assert((*foo).bar == 42);

	// No dereferencing! eh?
	assert(foo.bar == 42);

	free(foo);
}

I've taken a look in the std lib and the second form is used a 
lot. Why don't you need to dereference the pointer 'foo' to reach 
its member 'bar'?


More information about the Digitalmars-d-learn mailing list