Sign in to follow this  
CastorX

C++ operator help

Recommended Posts

Hello! simple C++ operator... I need some help. Q.: Which is correct? And Which is commonly used. XVector operator + (const XVector& vec) const { XVector tmp; tmp.x = x + vec.x; tmp.y = y + vec.y; tmp.z = z + vec.z; return tmp; } OR XVector& operator + (const XVector& vec) const { XVector tmp; tmp.x = x + vec.x; tmp.y = y + vec.y; tmp.z = z + vec.z; return tmp; } Thx.

Share this post


Link to post
Share on other sites
The first. Binary + should return a new object, not a reference. Regardless of operator etiquette, the second is returning a reference to a local, which is a pretty bad thing.

However, generally binary + would be implemented as a free function and implemented using the += operator:


XVector operator+(const XVector &A,const XVector &B)
{
XVector C=A; C+=B; return C;
}


Obviously += needs to be implemented, but the implementation of that should be more obvious.

The less stuff you implement as member functions, the less stuff you have depending upon internal details of the objects in question, so as a general rule, if you can implement an operator as a free function, it is probably a good idea.

HTH

Share this post


Link to post
Share on other sites
Returning a reference to a local variable is bad mojo. As soon as the function exits, the local variable's value is undefined... but then the next thing that happens is that its value is read, to assign to the result variable or wherever you're using it. This is one of those particularly bad bugs that will work "sometimes", and then pop up in response to a seemingly unrelated change. Luckily, most compilers catch this situation and issue a warning. Make sure that whatever compiler you're using, you set warnings to a high level (-Wall on GCC, level 3 on MSVC [level 4 is just stupid]).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this