C ++:在脚本中发生exception:basic_string :: _ S_construct NULL无效

我从数据库函数返回一个string或NULL到主程序,有时我从exception中得到这个错误:

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值和一个空字符串,那么你将不得不使用指针(聪明的,最好),或者,你可以使用boost::optional

这违反了std::string的约定,从空char指针构造它。 只要返回一个空字符串,如果你想要构造它的指针是null。

例如

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

我会尝试改变它返回一个空字符串,而不是null,并检查字符串的长度。