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

kri*_*itx 22 c++ linux

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

basic_string::_S_construct NULL not valid
Run Code Online (Sandbox Code Playgroud)

我认为它是因为从数据库函数返回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;
}
Run Code Online (Sandbox Code Playgroud)

Arm*_*yan 24

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

return string();
Run Code Online (Sandbox Code Playgroud)

要么

return "";
Run Code Online (Sandbox Code Playgroud)

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

  • 只是为了澄清,有一个_available_从`NULL`到`std :: string`的隐式转换,因为`std :: string`有一个非显式构造函数,它带有`const char*`,````将转换为.问题是`NULL`不适合与此构造函数一起使用,因为它违反了前提条件. (8认同)

CB *_*ley 12

std::string从空char指针构造它是违反合同的.如果要构造它的指针为null,则返回一个空字符串.

例如

return p == NULL ? std::string() : std::string(p);
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢`return std :: string(p?p:"");`因为这是一个稍微简单的返回表达式,可能有助于RVO. (2认同)
  • 或者甚至更短一点,所谓的 [elvis operator](https://en.wikipedia.org/wiki/Elvis_operator#C) `return std::string(d?:"");` (2认同)