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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12052997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:07:19  来源:igfitidea点击:

C++ : Exception occurred in script: basic_string::_S_construct NULL not valid

c++linux

提问by krisdigitx

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

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

basic_string::_S_construct NULL not valid

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

我认为这是因为从数据库函数返回 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;
}

采纳答案by Armen Tsirunyan

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

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

return string();

or

或者

return "";

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

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

回答by FaddishWorm

I would try changing it to return an empty string instead of null and check the string length.

我会尝试将其更改为返回一个空字符串而不是 null 并检查字符串长度。

回答by CB Bailey

It's a violation of std::string's contract to construct it from a null charpointer. Just return an empty string if the pointer that you want to construct it from is null.

std::string从空char指针构造它违反了的契约。如果要从中构造它的指针为空,则只返回一个空字符串。

E.g.

例如

return p == NULL ? std::string() : std::string(p);