TOFFY0312
TOFFY0312

Reputation: 3

Does this function returns a proper R-value reference or does it returns a copy?

Quaternion&& GetInverse() const
{
     return Quaternion( GetConjugate() / GetSquaredMagnitude() ); 
}

I wanna know what will be returned, and if it is more efficient to indeed return an Rvalue, or to simply return a copy.

Or maybe I am completely wrong and there simply is no copy here. Any information will be greatly appreciated. ^^;

Upvotes: 0

Views: 82

Answers (1)

Evg
Evg

Reputation: 26302

Quaternion&& is an r-value reference, but it is still a reference. In your code example you're returning a reference to a temporary object that will be destoroyed after GetInverse() returns and the reference will dangle. It is not an optimization, it is undefined behaviour.

Modern compilers are able to detect such errors. For example, GCC complains:

warning: returning reference to temporary [-Wreturn-local-addr]
    8 |      return Quaternion();

Returning by value is the best option here. Since C++17 copy elision is mandatory in such cases.

Upvotes: 4

Related Questions