FAQ 32.09 Should template functions for things like min(x,y) or abs(x) return a const reference?No! When the following example is compiled and the symbol UNSAFE is defined, min(x,y) avoids an extra copy operation by returning a const reference parameter by const reference. As discussed in the previous FAQ, this can create a dangling reference, which can destroy the world. #ifdef UNSAFE template<class T> inline const T& min(const T& x, const T& y) { return x < y ? x : y; } #else template<class T> inline T min(const T& x, const T& y) { return x < y ? x : y; } #endif Returning a const reference to a const reference parameter is normally done as an optimization to avoid an extra copy operation. If you're willing to sacrifice correctness, you can make your software very fast! |