Pointer types [Was: Re: Lints, Condate and bugs]

bearophile bearophileHUGS at lycos.com
Sun Oct 31 15:55:06 PDT 2010


Walter:

> Microsoft's Managed C++ does exactly this. While a technical success, it is a
> complete failure in regards to pleasing programmers.
> 
> I'm also very familiar with using multiple pointer types, which are a necessity
> for DOS programming. I'm sick of it. It sucks. I don't want to go back to it,
> and I don't know anyone who does.

I was talking about a different kind of pointer types, something not related to the CPU/OS.

Three possible annotations for pointers:

- @single: this pointer is either null or points to a single element of the base type (this disallows the indexing [] syntax).
- @bound(hi,lo): this pointer is either null or points inside an array of given lower and upper bounds.
- @sentinel: this pointer is useful only for comparisons and not for dereference or indexing. This annotation is usually used for pointers that point immediately after an allocated area.


You may implement them with just struct templates:


static assert(SinglePtr!int.sizeof == size_t.sizeof);
static assert(BoundPtr!int.sizeof == (size_t.sizeof * 3));
static assert(SentinelPtr!int.sizeof == size_t.sizeof);

int x;
SinglePtr!int p = singlePtr(&x);
SentinelPtr!int s = sentinelPtr(&(x) + 1);
int[5] a;
BoundPtr!int r1 = boundPtr(a);
BoundPtr!int r2 = boundPtr(a, 1, 4);


They are useful if you write low-level code in D, or if you want to use C libraries through D in a safer way (probably lot of C code will be used from D in the next years). I have implemented BoundPtr some time ago for D2.

Other possible features for them:
- head const
- tail const
- const
- no pointer arithmetic
- not null


The advantage of using struct templates is that there is no need to change D2. A disadvantage of using structs is that they can't be used in C function signatures (and their syntax is more heavy):

extern(C) void foo(@singleptr int*, @boundptr(10) int*);

Bye,
bearophile


More information about the Digitalmars-d mailing list