dimanche 26 septembre 2021

Why is a function taking a pointer preferred over a function taking an array reference?

Consider the following program:

#include <iostream>
#include <cstring>
using namespace std;

void print(const char *pa) { 
        cout << "Print - using pointer" << endl;
}

void print(const char (&arr)[]) {
        cout << "Print - using reference" << endl;
}

int main() { 
        char ca[] = {'B', 'A', 'D', 'C', '\0'};
        print(ca);
}

Results:

Print - using reference

Why is reference preferred over pointers?
According to C++ Primer 5th Ed., section 6.6.1:

In order to determine the best match, the compiler ranks the conversions that could be used to convert each argument to the type of its corresponding parameter. Conversions are ranked as follows:

  1. An exact match. An exact match happens when:
    • The argument and parameter types are identical.
    • The argument is converted from an array or function type to the corresponding pointer type. (§ 6.7 (p. 247) covers function pointers.)
    • A top-level const is added to or discarded from the argument.
  2. Match through a const conversion (§ 4.11.2, p. 162).
  3. Match through a promotion (§ 4.11.1, p. 160).
  4. Match through an arithmetic (§ 4.11.1, p. 159) or pointer conversion (§ 4.11.2, p. 161).
  5. Match through a class-type conversion. (§ 14.9 (p. 579) covers these conversions.)

No mentioned of reference here. Any idea?
Thanks

Aucun commentaire:

Enregistrer un commentaire