Question
Why does the compiler prefer f(const void*) to f(const std::string &)?
Consider the following piece of code:
#include <iostream>
#include <string>
// void f(const char *) { std::cout << "const char *"; } // <-- comment on purpose
void f(const std::string &) { std::cout << "const std::string &"; }
void f(const void *) { std::cout << "const void *"; }
int main()
{
f("hello");
std::cout << std::endl;
}
I compiled this program using g++ (Ubuntu 6.5.0-1ubuntu1~16.04) 6.5.0 20181026
:
$ g++ -std=c++11 strings_1.cpp -Wall
$ ./a.out
const void *
Note that the comment is there on purpose to test, otherwise the compiler uses f(const char *)
.
So, why does the compiler pick f(const void*)
over f(const std::string &)
?
46 1363
46