Advertisement

overloaded operator optimization (ooo)

Started by December 28, 2000 05:49 PM
2 comments, last by farmersckn 24 years ago
  
// which is faster:


// provided Point (int, int) is defined as:

// Point (int _X, int _Y)

// : X (_X), Y (_Y)

// {}

const Point & Point::operator += (const Point & ptRHS)
{
  return (Point (X += ptRHS.X, Y += ptRHS.Y));
}

// or this?

const Point & Point::operator += (const Point & ptRHS)
{
  X += ptRHS.X;
  Y += ptRHS.Y;
  return (*this);
}
// or is there another way?  a faster way?

// Thanks, I appreciate the help.

  
farmersckn
Yesterday is the past, tomorrow is the future. Today is a gift, that is why we call it the present.
I believe the first one is wrong so it doesn''t make much differance. Consider the following:

  (apoint += Point(1,1)).Rotate(anangle);  


What got rotated? apoint or a copy of apoint?
Keys to success: Ability, ambition and opportunity.
Advertisement
Well, I don''t know how you would rotate a point, but anyway...
It looks to me like you added 1, 1 to the coordinates of apoint and then called rotate on apoint. Since Point (1, 1) is the same as a constant, such as 4 or 5, you can''t call Rotate () on it.
Yesterday is the past, tomorrow is the future. Today is a gift, that is why we call it the present.
His point was that your first operator is returning a temporary function-local object. This is a no-no.

If you use your first operator +=, this is what will happen:
Point a (1,1);
Point b (1,1);
const Point &ref = (a += b);

At this point, a.X = 2, a.Y = 2. But ref is undefined, when it should be a reference to a.

You''re just overloading += the wrong way. Unless you''re doing some funky lazy evaluation, operator += should generally return *this. And I''m pretty sure it doesn''t need to return a const reference, just a reference.

Read Scott Meyer''s "Effective C++". It shows you the proper, most efficient way to implement a user type like you are trying to do here.

This topic is closed to new replies.

Advertisement