views:

54

answers:

1

From Herb Sutter's GotW #6

Return-by-value should normally be const for non-builtin return types. ...

Note: Lakos (pg. 618) argues against returning const value, and notes that it is redundant for builtins anyway (for example, returning "const int"), which he notes may interfere with template instantiation.

While Sutter seems to disagree on whether to return a const value or non-const value when returning an object of a non-built type by value with Lakos, he generally agrees that returning a const value of a built-in type (e.g const int) is not a good idea.

While I understand why that is useless because the return value cannot be modified as it is an rvalue, I cannot find an example of how that might interfere with template instantiation.

Please give me an example of how having a const qualifier for a return type might interfere with template instantiation.

+1  A: 

Here's a simple example involving function pointers:

const int f_const(int) { return 42; }
int f(int) { return 42; }

template <typename T>
void g(T(*)(T))
{
    return;
}

int main()
{
    g(&f_const); // doesn't work:  function has type "const int (*)(int)"
    g(&f);       // works: function has type "int (*)(int)"
}

Note that Visual C++ 2010 incorrectly accepts both. Comeau 4.3.10 and g++ 4.1.2 correctly do not accept the g(&f_const) call.

James McNellis