// 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
overloaded operator optimization (ooo)
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:
What got rotated? apoint or a copy of apoint?
(apoint += Point(1,1)).Rotate(anangle);
What got rotated? apoint or a copy of apoint?
Keys to success: Ability, ambition and opportunity.
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.
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.
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
Popular Topics
Advertisement
Recommended Tutorials
Advertisement