【发布时间】:2015-11-07 16:30:47
【问题描述】:
我盯着它并试图在 SO 上找到类似的问题,但没有发现任何有用的东西。所以,在这里发布我的问题。
考虑这个程序:
#include <iostream>
void foo(const std::string &) {}
int main()
{
foo(false);
}
[警告] 将 'false' 转换为 'std::basic_string::basic_string(const _CharT*, const _Alloc&) 的参数 1 的指针类型 [with _CharT = char; _Traits = std::char_traits; _Alloc = std::allocator]' [-Wconversion-null]
为什么 C++ 允许在没有显式转换的情况下这样做?我期待得到编译器错误。由于异常显示如下,程序在运行时异常终止:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
标准对这种类型的隐式转换有何规定?
【问题讨论】:
-
“标准对这种类型的隐式转换有何规定?” 它说是允许的。
-
@Downvoters:为什么要投反对票?有什么问题?
-
在 gcc 上,例如:melpon.org/wandbox/permlink/axWuSF1Nalk1Gr74。也许原因是
false可以隐式转换为const char*作为空指针。 -
您可以查看this
-
@PravasiMeet 我不是在谈论终止。我说的是编译。如果它编译,那么你应该期待一个异常终止,因为当你从空指针实例化一个字符串时会发生这种情况。
标签: c++ string boolean language-lawyer implicit-conversion