FAQ 32.09 Should template functions for things like min(x,y) or abs(x) return a const reference?

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!



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net