1

The following code gives me a warning about passing a temporary as a parameter to a function which takes a reference:

struct TempObject
{
    typedef TempObject& reference;

    const int First, Second;

    TempObject(int first, int second) : First(first), Second(second) {}
};

void Function(const TempObject::reference ref) 
{ 
    std::cout<< ref.First << ref.Second; 
}

int main(int argc, char *argv[])
{
    Function(TempObject(1, 2));  // warning is given here
}

This confuses me, because Function is in fact accepting a const TempObject::reference. Changing the definition of TempObject::reference to typedef const TempObject& reference causes the compiler to no longer emit the warning.

Why is there a difference? I found this behavior with Microsoft's and Intel's compilers.

bfair
  • 1,101
  • 7
  • 16
  • If you compile it with clang you get: `main.cpp:12:15: warning: 'const' qualifier on reference type 'TempObject::reference' (aka 'TempObject &') has no effect [-Wignored-qualifiers]` so no, `Function` isn't taking a const TempObject&. I'm not sure why though, so here's a +1. – Borgleader Jan 18 '15 at 01:46
  • That's a much better warning message. Why does the const qualifier have no effect? – bfair Jan 18 '15 at 01:47
  • 3
    The `const` applies to the instance of `TempObject::reference` itself, not to the `TempObject` instance it references. Of course a reference is unchangeable so the `const` is essentially meaningless. – Steve Vinoski Jan 18 '15 at 01:48
  • it's basically the same issue as with `typedef int* ip`, then `const ip variable` declares `variable` as a `const` pointer to `int` (the pointer itself is `const`, not the data it points to, i.e. you have a `int * const`). – vsoftco Jan 18 '15 at 01:58

0 Answers0