.ptr and .value

strtr strtr at spam.com
Wed May 5 15:58:03 PDT 2010


Robert Clipsham Wrote:

> On 05/05/10 23:20, strtr wrote:
> > I keep on expecting .ptr to work on all types. What keeps this from being the case?
> > And how about having a .value(.deref) property for known pointers?
> >
> > I feel a lot less comfortable with using stars and ampersands, because I keep on forgetting which one does what.
> 
> .ptr is only available for arrays. Internally, (dynamic) arrays in D 
> look like this:
> ----
> struct {
>    size_t length;
>    T* ptr;
> }
> ----
> Where T is the type of the array. This is why you can use .ptr on it. 
> For other types they are types on their own, so don't have such 
> properties. As for .value and .deref, these won't be implemented, you'll 
> have to live with & and * if you want to use pointers. Note that if 
> you're using pointers you should be comfortable with them, if you're not 
> it's probably best to avoid them. In fact, D makes it easy to do so!
I actually made this a while ago :)
http://bayimg.com/NaeOgaaCC

> 
> As for referencing/dereferencing:
> ----
> int myInt = 6;
> int* ptrToMyInt = &myInt; // & takes a reference to myInt, making
>                            // this a pointer
> int myInt2 = *myInt; // myInt2 == 6, * dereferences.
> ----

But wouldn't this (property sugar?) be nice?

int myInt = 6;
int* ptrToMyInt = myInt.ptr;
int myInt2 = ptrToMyInt.deref; // you probably didn't mean *myInt ;)

> Again, let me reinforce that you don't need to use pointers in D, 
Especially when interfacing with c libs, I'm forced to use *& often :(
Also *this is necessary to deref the this pointer within structs and classes.
On the other hand I don't remember using ** or && for quite some time.

> they're easy to avoid in most cases... Feel free to play with them, and 
> as you gain confidence you may find uses for them :) When I first 
> learned how to use pointers I found this little video/tutorial a fun 
> intro to them, you might like to take a look: 
> http://cslibrary.stanford.edu/104/ :)

I understand the concept of pointers, but I just keep forgetting which one to use * or &. probably because  I don't like the double * meaning.  



More information about the Digitalmars-d-learn mailing list