[英]Is it safe to overload char* and 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.
出于好奇,我想问一下char *和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;
}
Yes, it's safe, as long as you make it const char*
, and actually often useful. 是的,它是安全的,只要你使它成为
const char*
,并且实际上通常很有用。 String literals cannot be converted to char*
since C++11 (and it was deprecated before that). 自C ++ 11以来,字符串文字无法转换为
char*
(之前已弃用)。
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). 将为字符串文字选择
const char*
重载,因为字符串文字是const char[N]
(其中N
是字符数)。 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
相比,它被认为是执行数组到指针转换的更好匹配。
Why can overloading std::string
and const char*
be useful? 为什么重载
std::string
和const char*
会有用? 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. 例如,如果你有一个
std::string
重载和一个bool
重载,那么当你传递一个字符串文字时会调用bool
。 That's because the bool
overload is still considered a better match than constructing a std::string
. 那是因为
bool
重载仍然被认为是比构造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. 我们可以通过提供一个
const char*
重载来解决这个问题,它将超过bool
重载,并且可以转发到std::string
重载。
Short Answer: Perfectly safe. 简答:完全安全。 Consider the following uses:
考虑以下用途:
foo("bar");//uses c string
foo(std::string("bar") );//uses std::string
char* bar = "bar";
foo(bar);//uses c string
std::string bar_string = "bar";
foo(bar_string);//uses std::string
foo(bar_string.c_str()); //uses c string
Word of warning, some compilers (namely those with c++11 enabled) require the const keyword in parameter specification in order to allow temporary strings to be used. 警告,一些编译器(即启用了c ++ 11的编译器)需要参数规范中的const关键字才能允许使用临时字符串。
For instance, in order to get this: foo("bar"); 例如,为了得到这个:foo(“bar”); You need this: void foo(const char* bar);
你需要这个:void foo(const char * bar);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.