[英]Why do char{} and char() work as a temporary variable for a char* argument?
In Visual C++ 2017 (with /std:c++14
or with /std:c++17
), the following code works: 在Visual C ++ 2017中(使用
/std:c++14
或使用/std:c++17
),以下代码可以正常工作:
void TakePtr(char*); // const or not
int main()
{
TakePtr(char{});
TakePtr(char());
}
I don't understand why it works. 我不明白为什么会这样。
Apparently, the following would also work (as expected): 显然,以下内容也可行(如预期):
void TakeChar(char);
TakeChar(char{});
TakeChar(char());
How does the compiler deduce (or convert) the type char
to char*
, when char{}
or char()
is used as an argument? 当
char{}
或char()
用作参数时,编译器如何将char
类型推导(或转换)为char*
?
Now, if I have both char
and char*
overloads, it works without any error/warning about ambiguity: 现在,如果我同时拥有
char
和char*
重载,它可以在没有任何关于歧义的错误/警告的情况下工作:
void TakePtr(char*);
void TakePtr(char);
TakePtr(char{}); // Chooses 'char'
TakePtr(char()); // Chooses 'char'
Why is the compiler okay with char{}
for TakePtr(char*)
? 为什么编译器可以使用
char{}
for TakePtr(char*)
? And why doesn't it give a warning/error when choosing the better version? 为什么在选择更好的版本时它不会给出警告/错误? Such behavior is bound to break existing code.
这种行为势必破坏现有代码。
For sure, the compiler isn't happy with: 当然,编译器不满意:
void TakePtr(char*);
char c{};
TakePtr(c);
Because Visual lies a lot. 因为视觉很重要。 Especially older one.
特别是老一个。 Your code prompts clang to report an error:
您的代码提示clang报告错误:
<source>:9:6: error: no matching function for call to 'TakePtr'
TakePtr(char{});
^~~~~~~
<source>:5:6: note: candidate function not viable: no known conversion from 'char' to 'char *' for 1st argument
void TakePtr(char*); // const or not
^
<source>:10:6: error: no matching function for call to 'TakePtr'
TakePtr(char());
^~~~~~~
<source>:5:6: note: candidate function not viable: no known conversion from 'char' to 'char *' for 1st argument
void TakePtr(char*); // const or not
^
2 errors generated.
Visual is known to be "wonky" in term of following C++ standard, so don't rely on it too much. 在遵循C ++标准方面,Visual被称为“不稳定”,所以不要太依赖它。 Try to verify with clang / gcc, just to be sure.
尝试用clang / gcc验证,只是为了确定。
This is simply MSVC being behind: the rule in C++03 was that any constant expression of integer type and value 0 was a null pointer constant and could thus be converted to char*
. 这就是MSVC落后:C ++ 03中的规则是整数类型和值0的任何常量表达式都是空指针常量,因此可以转换为
char*
。 Certainly char()
qualifies—and char{}
means the same thing, although it never overlapped with the rule. 当然
char()
限定 - 和char{}
意味着相同的事情,虽然它从不与规则重叠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.