[英]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.