re-creating C++'s reference bahavior
swiftcoder
swiftcoder at darkcoda.com
Tue Apr 17 11:25:46 PDT 2007
Except of course that opAssign is not overload-able in this manner.
swiftcoder Wrote:
> What it really gets down to, is that I don't want to increase the code complexity needlessly. For many reasons, there shouldn't be a copy made when all we want to do is query a member, and we musn't have a copy when we set a member:
>
> float x = n.position.x; // or:
> n.position.x = 10;
>
> But we do want a copy when we request the whole vector:
>
> Vector3f v = n.position;
>
> So maybe the best thing is to override opAssign() to copy (thus behaving like a struct). Then the olnly thing to make sure is that functions taking a vector as an 'in' argument make a local copy rather than modifying the argument directly. And since opAdd, etc. already produce new vectors, I don't think that will be much of a problem.
>
> Does this make sense to you?
>
> Derek Parnell Wrote:
>
> > On Mon, 16 Apr 2007 20:47:31 -0400, swiftcoder - Tristam MacDonald wrote:
> >
> > > I am fairly new to D, from a C++ background, and I am having a
> > > hard time coming up with a sensible way to deal with what is
> > > a fairly trivial example in C++:
> > > ...
> > > But now in D, I find that the last statement requires ...
> >
> > Does this below help any?
> >
> > ////////////////////
> > import std.stdio;
> >
> > class Vector3f
> > {
> > int x;
> > float y;
> > }
> >
> > class Node
> > {
> > Vector3f m_position; // (reference to) a Vector
> > Vector3f position() // Copy-getter
> > {
> > Vector3f t = new Vector3f;
> > // copy fields by hand
> > t.x = m_position.x;
> > t.y = m_position.y;
> >
> > return t;
> > }
> >
> > Vector3f* position_flds() // Reference-getter
> > {
> > return &m_position;
> > }
> >
> > this() { m_position = new Vector3f; }
> > }
> >
> > void main()
> > {
> > Node n = new Node;
> >
> > writefln("A %s %s", n.position.x, n.position.y);
> > n.position_flds.x = 1;
> > n.position_flds.y = 2.2;
> > writefln("B %s %s", n.position.x, n.position.y);
> >
> > Vector3f v = n.position;
> > writefln("C %s %s", v.x, v.y);
> > v.x = 10;
> > v.y = 9.9;
> > writefln("D %s %s", v.x, v.y);
> > writefln("E %s %s", n.position.x, n.position.y);
> > }
> > ///////////////////
> >
> >
> > --
> > Derek
> > (skype: derek.j.parnell)
> > Melbourne, Australia
> > "Justice for David Hicks!"
> > 17/04/2007 5:30:04 PM
>
More information about the Digitalmars-d-learn
mailing list