我有一个函数foo(const std::string& str);
如果你使用它调用它它会崩溃foo(NULL)
.
我该怎么做才能防止它崩溃?
std::string 有一个采用 const char* 参数的构造函数。当您将 NULL 传递给它时,该构造函数将会崩溃,并且当您编写 foo(NULL) 时,会隐式调用该构造函数。
我能想到的唯一解决方案是重载 foo
void foo(const std::string& str)
{
// your function
}
void foo(const char* cstr)
{
if (cstr == NULL)
// do something
else
foo(std::string(cstr)); // call regular funciton
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)