c++ - 为什么编译器更喜欢 f(const void*) 而不是 f(const std::string &)?

标签 c++ stdstring string-literals overloading overload-resolution

考虑以下代码:

#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;
}

我使用g++ (Ubuntu 6.5.0-1ubuntu1~16.04) 6.5.0 20181026编译了这个程序:

$ g++ -std=c++11 strings_1.cpp -Wall
$ ./a.out

const void *

请注意,注释是为了测试而存在的,否则编译器会使用 f(const char *)

那么,为什么编译器会选择 f(const void*) 而不是 f(const std::string &)

最佳答案

转换为 std::string 需要“用户定义的转换”。

转换为 void const* 不会。

用户定义的转换在内置转换之后排序。

关于c++ - 为什么编译器更喜欢 f(const void*) 而不是 f(const std::string &)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53354226/

相关文章:

c++ - pthread_cond_broadcast 是如何工作的?

c++ - 如何使用 log4cplus 在日志文件中打印方法名称

c++ - std::string::reserve 和字符串结尾 0

c++ - 以本地化安全的方式将字符串/字符与 C++ 中的字符串/字 rune 字进行比较

java - 为什么 "\400"不是编译时错误?

c++ - 如何在不违反C++中的DRY原则的情况下实现可移动重载?

C++调用函数导致调用另一个函数

c++ - 使用 copy_if 复制 std::string(到另一个字符串)

c++ - 为什么通过流获取的 std::string 被覆盖?

objective-c - Objective-C 是否使用字符串池?