C ++:在脚本中发生异常:basic_string :: _ S_construct NULL无效 [英] C++ : Exception occurred in script: basic_string::_S_construct NULL not valid

查看:1497
本文介绍了C ++:在脚本中发生异常:basic_string :: _ S_construct NULL无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am returning a string or NULL from the database function to the main program, sometimes i get this error from the exception:

basic_string::_S_construct NULL not valid

我认为它是因为从数据库返回NULL值功能?任何想法

i think its because of the return NULL value from the database function? any ideas???

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;
}


推荐答案

$ c> NULL (或 0 因为没有适当的隐式转换。您可能想要返回一个空字符串

You cannot return NULL (or 0) from a function that is declared to return string because there is no appropriate implicit conversion. You might want to return an empty string though

return string();

return "";

如果你想能够区分 NULL value和一个空字符串,那么你将不得不使用指针(聪明的,最好),或者,你可以使用 boost :: optional

If you want to be able to distinguish between a NULL value and an empty string, then you will have to use either pointers (smart ones, preferrably), or, alternatively, you could use boost::optional

这篇关于C ++:在脚本中发生异常:basic_string :: _ S_construct NULL无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆