在VS2015和VS2017上,此编译没有警告,并生成无法捕获的访问冲突并导致应用程序崩溃.显然,int 0被静默转换为空指针,然后假定它指向一个字符串,从而崩溃.
#include <string>
#include <iostream>
void crash(const std::string& s) {}
int main()
{
try
{
crash(0);
}
catch (const std::exception& ex)
{
// never gets here!
std::cout << "got" << ex.what() << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
如何从这样的异常中捕获并恢复?如果我从函数参数中删除const它不会编译 - 所以这可能是防止用户滥用的一种方法,但是我会失去const提供的保护,或者我会吗?编写避免此问题的原型的最佳做法是什么?
c++ ×1