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