问题场景
从mysql数据库中读取字符数据保存到string类型的时候出现terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid
问题解决
使用typeid().name发现从mysql读取出的数据为char
∗
*
∗类型。当我的查询字段没有值时,指针为NULL。
如果使用string s = string(char*)
赋值,char
∗
*
∗为NULL就会报上述错误。因此进行以上赋值操作时应先检验是否为空指针。
#include <iostream>
#include <string>
using namespace std;
int main() {
char *s2 = NULL;
string str(s2);
cout << str << endl;
}