How to be more careful about null pointers?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Mar 29 12:09:35 PDT 2016
On 03/29/2016 11:57 AM, cy wrote:
> On Tuesday, 29 March 2016 at 06:21:49 UTC, Ali Çehreli wrote:
>> parent.prep.bind is translated to the following by the compiler:
>>
>> "Call bind() for the object at address... let's calculate... Wherever
>> parent is, we should add the offset of prep inside that object."
>
> Okay, that's helpful actually. So, when accessing members of an object,
> it won't trigger a NPE, because the object is not dereferenced
> immediately, but the expected offset to the member is dereferenced. D
> puts off resolving pointer addresses as much as possible, so instead of
> bind((*parent).(*prep)) it's more like bind(parentlocation + prepoffset)
> and only (this.)member resolves to (*(parentlocation +
prepoffset).member).
>
> I thought it had an extra layer of pointer indirection, like if class
> object A has address 1234,
The class object would be sitting at that address. Our access to it is
through a class variable:
Foo var = new Foo();
Although you don't see a pointer in sight, behind scenes 'var' is
nothing but a pointer.
> and member A.b has offset 0x20, then you
> first dereference address 1234 (to get 4321 say) and then add 0x20 to
> that.
No, there is no dereferencing of 'var'. However, you could have 'Foo*',
which would be the equivalent of a "pointer to pointer" in C.
> But actually a class object is... already dereferenced, and is an
> integer representing the address to the object, not a pointer to that
> address.
Correct.
> Variables representing fixed, definite memory locations really throws me
> sometimes. You can't assign to a const, because that assigns to const
> marked memory
The object *may* really be on const-marked memory but not necessarily.
You can have const variables anywhere; the const access is checked at
compile time.
> and doesn't just move the variable somewhere else.
That does not happen for various reasons. Firstly, if we could mutate,
what would 'const' mean? Then, the compiler would have to have a
complete view of the program to update all other references, which would
be slow and the semantics would be difficult.
> And
> NPE doesn't occur with a class, because setting it to NULL, and
> accessing a member is more like this in C:
>
> intptr_t a = 0;
> (struct B*)(a+0x20).member
>
> and less like this in C:
>
> intptr_t* a = 0;
> (struct B*)(*a+0x20).member
Yes.
Ali
More information about the Digitalmars-d-learn
mailing list