operator*, +, -, etc... all need to return by value. there is no other
way to do it - since returning ref to temporary is invalid.
you can optimize it though if it is inline by returning a constructor.
then the compiler will make one less temporary.
// slower
Vec3f Vec3f::operator-( const Vec3f& rhs )
{
Vec3f temp;
temp[0] = vec[0] - rhs.vec[0];
temp[1] = vec[1] - rhs.vec[1];
temp[2] = vec[2] - rhs.vec[2];
return temp;
}
// faster because of the return value optimization
Vec3f Vec3f::operator-( const Vec3f& rhs )
{
return Vec3f( vec[0] - rhs.vec[0], vec[1] - rhs.vec[1], vec[2] - rhs.vec[2] );
}
of course, -= is the fastest since it does it by reference:
// fastest
Vec3f& Vec3f::operator-=( const Vec3f& rhs )
{
vec[0] -= rhs.vec[0];
vec[1] -= rhs.vec[1];
vec[2] -= rhs.vec[2];
return *this;
}
if you want to see an example, or just use a math lib that has already
been built see the isugamedev/lib/math directory in CVS. It has Vec2,
Vec3, Vec4, Matrix, Quat, and some others...
kevin
@--@---@---@----@-----@------@------@-----@----@---@---@--@
Kevin Meinert __ _ __
http://www.vrac.iastate.edu/~kevn \ || \| \ / `
Virtual Reality Applications Center \ ||.-'|--\
Howe Hall, Iowa State University, Ames Iowa \|| \| \`__,
-----------------------------------------------------------
On Wed, 13 Feb 2002, Andres Reinot wrote:
> 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?
>
|