[英]c++ passing a string literal instead of a const std::string&?
[英]Exception on passing a bool to a const std::string&
上周我有一個有趣和可思考的時刻......我不明白發生了什么。 也許你們中的某個人可以給我一些線索。
我寫了一個像這樣的函數(簡化):
void read(const std::string& sSource, std::string& sResult, bool bCheck = true)
然后我用這樣的另一個參數擴展了這個函數
void read(const std::string& sSource, std::string& sResult, const std::string& sIPAdress, bool bCheck = true)
我忘了在我的程序中更改一個函數調用,所以它叫做“read”:
read("/file/sepp.dat", sResult, false);
如您所見,我將一個false
傳遞給const std::string
引用。
是的,默認參數不好,但這不是重點。
我有一個例外(我不記得確切的輸出):
“無法使用nullptr初始化std :: string”或者......
所以現在有四個問題,我無法自己回答:
1.)怎么可能,編譯器沒有發出警告?
2.)為什么類型系統無法找到, bool
不應該以這種方式“進入” string
?
3.)為什么這只發生在const std::string&
,而不是std::string&
參數? (使用非const
std::string
存在編譯器錯誤)
4.)是否有可能使用bool
傳遞給const std::string
引用,使編譯器認為,這可能是正確的?
1)允許從bool
到const char*
的隱式轉換。 不幸的是,這是該語言的一個特征。
2)因為存在從bool
到const char*
的隱式轉換,並且std::string
有一個構造函數,它將const char*
作為參數。 它假定它指向一個有效的以null結尾的字符串,這就是您看到運行時錯誤的原因。
3)因為該語言不允許將臨時對象綁定到非const左值引用。 但是,Id允許將const左值引用綁定到臨時值。
4)由於上述所有原因,編譯器已經認為它是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.