Void pointers

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 17 11:25:46 PDT 2016


On 05/17/2016 07:43 PM, Alex wrote:
> The relation is: some object A contains the pointer/iota/(if at all)
> some object B makes slices of the thing, which is in A.

Ok, so you have some object that stores a void pointer. The pointer is 
going to be null at all times. Then you slice that pointer. Is that right?

In code:
----
class C
{
     void* ptr = null; /* always going to stay null */
     void[] getSlice(size_t a, size_t b) { return ptr[a .. b]; }
}

void main()
{
     auto c = new C;
     void[] slice1 = c.getSlice(5, 10);
     void[] slice2 = c.getSlice(7, 21);
}
----

Now you see a relation/dependency between slice1 and slice2, because the 
pointer they slice is the same, and it's stored in the same C object, right?

But when slicing a pointer what matters is the value of the pointer, not 
where it resides. Where the pointer is stored is completely irrelevant. 
Like when adding two ints it doesn't matter where they came from; only 
their values matter.

Calling getSlice(5, 10) on two different C objects will return the 
exactly same slice (as long as ptr stays null):

----
/* ... class C as above ... */

void main()
{
     auto c1 = new C;
     auto c2 = new C;
     assert(c1 !is c2); /* not the same object */
     assert(c1.getSlice(5, 10) is c2.getSlice(5, 10)); /* but the exact 
same slice */
}
----

There is no relationship between the slices or between a slice and the 
object that created it. You can have a free function that returns the 
exact same slices again:

----
/* ... class C as above */

void[] freeGetSlice(size_t a, size_t b)
{
     void* ptr = null;
     return ptr[a .. b];
}

void main()
{
     auto c = new C;
     assert(c.getSlice(5, 10) is freeGetSlice(5, 10));
}
----

A note on iota: If you use iota instead, you don't need to store the 
result in the object either. You can call iota on the spot just like you 
call getSlice.


More information about the Digitalmars-d-learn mailing list