一尘不染

C ++:脚本中发生了异常:basic_string :: _ S_construct NULL无效

linux

我从数据库函数返回字符串或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;
}

阅读 507

收藏
2020-06-07

共1个答案

一尘不染

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

return string();

要么

return "";

如果要能够区分一个NULL值和一个空字符串,则必须使用指针(最好是智能指针),或者可以使用boost::optional

2020-06-07