【发布时间】:2019-06-17 11:38:02
【问题描述】:
由于一个错误,我刚刚发现这段代码在 Visual Studio 17 上编译得很好,而且可能在其他编译器上也是如此。现在我很好奇为什么?
#include <iostream>
#include <string>
std::string foo(){
return nullptr;
}
int main(){
auto s = foo();
std::cout << s << std::endl;
}
我可以想象这是因为std::basic_string c'tor 可以使用char* 调用,并且在返回从ptr 到std::string 的隐式转换时发生(使用NULL 作为参数,然后发出嘘声)。我走对了吗?
【问题讨论】:
-
它可能确实将
nullptr作为指针的参数传递 -
它可以编译,但是你得到一个运行时错误。
-
添加
string (nullptr_t) = deletector 可能会有所帮助,以便在编译时捕获此错误。我认为合法程序不会因此而中断。
标签: c++ function language-lawyer stdstring