gpt4 book ai didi

C++:脚本中发生异常:basic_string::_S_construct NULL 无效

转载 作者:IT老高 更新时间:2023-10-28 21:39:31 25 4
gpt4 key购买 nike

我从数据库函数返回一个字符串或 NULL 到主程序,有时我从异常中得到这个错误:

basic_string::_S_construct NULL not valid

我认为是因为数据库函数返回 NULL 值?有什么想法???

string database(string& ip, string& agent){
//this is just for explanation
.....
....

return NULL or return string

}

int main(){
string ip,host,proto,method,agent,request,newdec;
httplog.open("/var/log/redirect/httplog.log", ios::app);

try{
ip = getenv("IP");
host = getenv("CLIENT[host]");
proto = getenv("HTTP_PROTO");
method = getenv("HTTP_METHOD");
agent = getenv("CLIENT[user-agent]");

if (std::string::npos != host.find(string("dmnfmsdn.com")))
return 0;

if (std::string::npos != host.find(string("sdsdsds.com")))
return 0;

if (method=="POST")
return 0;

newdec = database(ip,agent);
if (newdec.empty())
return 0;
else {
httplog << "Redirecting to splash page for user IP: " << ip << endl;
cout << newdec;
cout.flush();
}
httplog.close();
return 0;
}
catch (exception& e){
httplog << "Exception occurred in script: " << e.what() << endl;
return 0;
}
return 0;
}

最佳答案

您不能从声明为返回 string 的函数返回 NULL(或 0),因为没有适当的隐式转换。您可能希望返回一个空字符串

return string();

return "";

如果您希望能够区分 NULL 值和空字符串,那么您将不得不使用指针(最好是智能指针),或者,您可以使用 std::optional (或 C++17 之前的 boost::optional)。

关于C++:脚本中发生异常:basic_string::_S_construct NULL 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12052997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com