Returning a struct by reference

Simon TRENY simon.treny at free.fr
Sat Mar 21 06:55:13 PDT 2009


Daniel Keep Wrote:

> 
> 
> Simon TRENY wrote:
> > Ok, but then, what if I'd like to make the variable "read-only"? i.e. preventing the user from writing things like this:
> > myObject.position = pos2;
> > 
> 
> So... you're rejecting a solution on the basis that it prevents you from
> doing the exact opposite of what you want to do?
> 
> *boggle*
> 
>   -- Daniel

Here is a complete example of what I'd like to achieve:
struct Position {
   private float m_x;
   private float m_y;

   public float x() {
      return m_x;
   }

   public void x(float x) {
      m_x = x;
      EmitSignal("changed");
   }

   public float y() {
      return m_y;
   }

   public void y(float y) {
      m_y = y;
      EmitSignal("changed");
   }
}

class Object {
   private Position m_position;

   public this() {
      m_position.CallOnSignal("changed", onPositionChanged);
   }

   //This syntax is not working
   public ref Position position() {
      return m_position;
   }

   public void onPositionChanged() {
      writeln("Position Changed!!);
   }
}

With this "fictional" code, I could write things like:
object.position.x = 14; and the object will be "aware" that its position has changed.

Making the "position"-variable public will lead the user to be able to do things like this:
object.position = pos2; and then, the object won't be "aware" that its position has changed. And this is a problem for me.

I hope it's clearer now



More information about the Digitalmars-d mailing list