[英]Why is it an error to construct an unassigned temporary instance of a class with a const char* variable when that class has a const char* constructor?
[英]Why do char{} and char() work as a temporary variable for a char* argument?
在Visual C ++ 2017中(使用/std:c++14
或使用/std:c++17
),以下代码可以正常工作:
void TakePtr(char*); // const or not
int main()
{
TakePtr(char{});
TakePtr(char());
}
我不明白为什么会这样。
显然,以下内容也可行(如预期):
void TakeChar(char);
TakeChar(char{});
TakeChar(char());
当char{}
或char()
用作参数时,编译器如何将char
类型推导(或转换)为char*
?
现在,如果我同时拥有char
和char*
重载,它可以在没有任何关于歧义的错误/警告的情况下工作:
void TakePtr(char*);
void TakePtr(char);
TakePtr(char{}); // Chooses 'char'
TakePtr(char()); // Chooses 'char'
为什么编译器可以使用char{}
for TakePtr(char*)
? 为什么在选择更好的版本时它不会给出警告/错误? 这种行为势必破坏现有代码。
当然,编译器不满意:
void TakePtr(char*);
char c{};
TakePtr(c);
因为视觉很重要。 特别是老一个。 您的代码提示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.
在遵循C ++标准方面,Visual被称为“不稳定”,所以不要太依赖它。 尝试用clang / gcc验证,只是为了确定。
这就是MSVC落后:C ++ 03中的规则是整数类型和值0的任何常量表达式都是空指针常量,因此可以转换为char*
。 当然char()
限定 - 和char{}
意味着相同的事情,虽然它从不与规则重叠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.