是否可以安全地重载char *和std :: string? [英] Is it safe to overload char* and std::string?

查看:295
本文介绍了是否可以安全地重载char *和std :: string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了关于初学者书上的重载函数。
只是出于好奇我想问是否是安全的在char *和std :: string之间重载。

I have just read about the overloading functions on a beginner book. Just out of curiosity I 'd like to ask whether it is safe to overload between char* and std::string.

我使用下面的代码,并得到一些结果。但我不知道这是否是一个未定义的行为。

I played with the below code and get some result. But I was not sure whether it is an undefined behavior.

void foo(std::string str) {
  cout << "This is the std::string version. " << endl;
}

void foo(char* str) {
  cout << "This is the char* version. " << endl;
}

int main(int argc, char *argv[]) {

  foo("Hello"); // result shows char* version is invoked

  std::string s = "Hello";
  foo(s); // result shows std::string version

  return 0;

}


推荐答案

它是安全的,只要你使它 const char * ,实际上通常有用。字符串文字不能从C ++ 11转换为 char * (在此之前已被弃用)。

Yes, it's safe, as long as you make it const char*, and actually often useful. String literals cannot be converted to char* since C++11 (and it was deprecated before that).

对于字符串字面量,将选择 const char * 重载,因为字符串字面量是 const char [N] 其中 N 是字符数)。重载有一种优先级顺序,当多个工作时,将选择哪一个。与构建 std :: string 相比,它被认为是执行数组到指针转换的更好的匹配。

The const char* overload will be picked for a string literal because a string literal is a const char[N] (where N is the number of characters). Overloads have a kind of priority ordering over which one will be picked when multiple would work. It's considered a better match to perform array-to-pointer conversion than to construct a std::string.

为什么可以重载 std :: string const char * 有用吗?例如,如果 std :: string 有一个重载, bool 有一个重载,则 bool 会在你传递一个字符串字面量时被调用。这是因为 bool 重载仍然被认为是比构造一个 std :: string 更好的匹配。我们可以通过提供 const char * 重载来克服这个问题,这将超过 bool 重载,到 std :: string 重载。

Why can overloading std::string and const char* be useful? If you had, for example, one overload for std::string and one for an bool, the bool would get called when you passed a string literal. That's because the bool overload is still considered a better match than constructing a std::string. We can get around this by providing a const char* overload, which will beat the bool overload, and can just forward to the std::string overload.

这篇关于是否可以安全地重载char *和std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆