From: Chad A. <ae...@ae...> - 2002-02-14 08:00:55
|
You want to return references for preincrement, predecrement, and all operator= variants (+=, *=, etc.). The others return the type by value. If you're returning an object by value, you should probably make it const so that you can't do things like: (v1 + v2).normalize(); // useless code! normalizes the temporary! Don't return a reference to a local object. Return it by [const] value. example code: Vector2f operator+(const Vector2f& lhs, const Vector2f& rhs) { return Vector2f(lhs.x + rhs.x, lhs.y + rhs.y); } Vector2f& operator=(Vector2f& lhs, const Vector2f& rhs) { lhs.x = rhs.x; lhs.y = rhs.y; return lhs; } > We're trying to re-make my vector library, right this time, with overloaded > functions. Now when I'm returning, I want to return a reference right? so > that I can chain my addition/subtraction etc.? But now for some functions I > don't actually want to change the values of *this, I want to return a > temporary vector I created in the operator+() function for example. Can I > return temp as a reference without problems of it going out of scope? What's > the best way of doing what I'm trying to do? |