# When to return a reference and when to return a copy?

I was looking at the d3dx math .h and noticed that a difference between the "+" and "+=" operators:

D3DXVECTOR3& operator += ( CONST D3DXVECTOR3& );
D3DXVECTOR3 operator + ( CONST D3DXVECTOR3& ) const;


Why is it returning a reference in the case of a += operation and a copy in the case of + operation ?

I'm guessing in the first case it's modifying the vector on which you call the += operation, something like this:

this->_x += x;
...
return *this;


and in the case of a + operation it would be doing something like this:

return D3DXVECTOR3(this->_x + x, this->_y + y, this->_z + z);


That being said, if that's what happens in the D3DXVECTOR3 implementation, why not return a reference in the case of + operation ?

You return a reference to the original vector in a += because you are modifying the actual vector itself and the vector will not fall out of scope.

While in a + you do not want any modification of the original vector. Instead a + operator computes a new value and uses copy constructors to return the value.

If you would try something like

D3DXVECTOR3 newVal = D3DXVECTOR3(this->_x + x, this->_y + y, this->_z + z);
return &newVal;


You would return a reference to a vector which fell out of scope and therefore will be cleaned up very soon.

• I guess I thought that as long as you had a ref to newVal it would not be able to be cleaned up since it would be referenced somewhere else. – dotminic Oct 29 '10 at 19:16
• In C++ classes/structs which do not allocate space for themselves with the "new" command will be cleaned up when the next "}" is seen. The problem is that even though it's cleaned up the values still exist in memory until something writes over that area. Which can lead to very hard to find bugs. – David Young Oct 29 '10 at 19:20
• Right so it's the same as in C. I should have figured that out. I'm moving up from C to C++ and was pretty unsure about that. Thanks for the info. – dotminic Oct 29 '10 at 19:35
• Ah then just to clarify, plain old C++ is like that, but not C++ .NET.... C++ .NET is garbage collected while plain old C++ requires new/delete – David Young Oct 29 '10 at 19:48

Why is a reference returned for += ?

A reference is returned because the object is (likely) being modified directly, and as such it wouldn't make sense to create a copy for the sole purpose of returning one.

Note that the reference can still be converted to a copy by other operations (such as =):

D3DXVECTOR3 a (1,2,3);
D3DXVECTOR3 b (1,2,3);

In the operator += case, the method is probably modifying the calling object in place. On the other hand, operator + is creating a new D3DXVECTOR3 that is the sum of the calling object and the argument.