Search code examples
c++c++11referencelanguage-lawyervalue-categories

Where does the standard define the order of preference for binding of values to references?


As it is explained here, values of different categories bind to references of different kinds according to the following order of preference:

struct s {};

void f (      s&);  // #1
void f (const s&);  // #2
void f (      s&&); // #3
void f (const s&&); // #4

const s g ();
s x;
const s cx;

f (s ()); // rvalue        #3, #4, #2
f (g ()); // const rvalue  #4, #2
f (x);    // lvalue        #1, #2
f (cx);   // const lvalue  #2

Where in the standard is this order of preference described?


Solution

  • [over.ics.rank]/3 - (3.1) Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if

    ...

    (3.1.3) — S1 and S2 are reference bindings (8.5.3) and neither refers to an implicit object parameter of a non-static member function declared without a ref-qualifier, and S1 binds an rvalue reference to an rvalue and S2 binds an lvalue reference.

    ...

    (3.1.6) — S1 and S2 are reference bindings (8.5.3), and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers.

    By these rules, a function taking rvalue reference is preferred over one taking lvalue reference, and then a function taking non-const reference is preferred over one taking const. Considering only overloads that are viable, of course.