Why does the compiler prefer f(const void*) to f(const std::string &)?

  • A+

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 &)?


Converting to a std::string requires a "user defined conversion".

Converting to void const* does not.

User defined conversions are ordered behind built in ones.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: