0

The following code does not compile:

typedef int& int_ref;

int main()
{
    const int& ic = 1;
    const int_ref icc = 2;
}

error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'.

When I move the const into the typedef it does compile, like so:

typedef const int& int_ref;

int main()
{
    const int& ic = 1;
    int_ref icc = 2;
}

Why??

Epic
  • 572
  • 2
  • 18
  • 6
    `typedef`s are not a textual replacement. The `const` in `const int_ref` applies to the reference (and is silently ignored). There's a dupe somewhere... – Max Langhof Sep 26 '19 at 09:01
  • 1
    "prog.cc:6:5: warning: 'const' qualifier on reference type 'int_ref' (aka 'int &') has no effect [-Wignored-qualifiers]" – Quentin Sep 26 '19 at 09:01
  • 1
    What you actually produced with your typedef is `int& const icc` (vs. `int const& ic`, if applying the paradigm of always placing const to the right of what it refers to). – Aconcagua Sep 26 '19 at 09:05
  • In any case, you shouldn't typedef references or pointers, it is bad practice and only hiding information without any further benefit – unless you explicitly *want* to hide the information, e. g. if having some kind of HANDLE (consider WinAPI) and you don't want anybody to know that there's actually some pointer hidden behind (perhaps you want to change it some day to an int?). – Aconcagua Sep 26 '19 at 09:08

0 Answers0