文字符号和字符串变量之间的串联然后 return const char*
A concatenation between a literal symbol and a string variable then return const char*
我想将文字符号“~”与字符串变量连接起来。
string dbFile = "data.db";
const char *temporaryFileName = ("~" + dbFile).c_str(); // it must be ~data.db
cout << temporaryFileName << endl;
没有错误,但是打印的时候什么也没有出来,为什么?
查看您使用的运算符 return 类型:
string operator+(const char* lhs, string& rhs); // untempletized for simplicity
请特别注意,它 return 是一个新对象。因此,表达式 ("~" + dbFile)
return 是一个新的临时对象。临时对象只存在到完整的表达式语句(除非被引用绑定)。在这种情况下,语句在同一行的分号处结束。
仅当指向的 string
对象仍然存在时,才允许使用由 c_str()
编辑的指针 return。您在字符串不再存在的下一行使用指针。行为未定义。
解决办法:要么修改原来的字符串,要么新建一个字符串对象。确保字符串对象至少在使用字符指针时存在。示例:
string dbFile = "data.db";
auto temporaryFileName = "~" + dbFile;
cout << temporaryFileName.c_str() << endl;
我想将文字符号“~”与字符串变量连接起来。
string dbFile = "data.db";
const char *temporaryFileName = ("~" + dbFile).c_str(); // it must be ~data.db
cout << temporaryFileName << endl;
没有错误,但是打印的时候什么也没有出来,为什么?
查看您使用的运算符 return 类型:
string operator+(const char* lhs, string& rhs); // untempletized for simplicity
请特别注意,它 return 是一个新对象。因此,表达式 ("~" + dbFile)
return 是一个新的临时对象。临时对象只存在到完整的表达式语句(除非被引用绑定)。在这种情况下,语句在同一行的分号处结束。
仅当指向的 string
对象仍然存在时,才允许使用由 c_str()
编辑的指针 return。您在字符串不再存在的下一行使用指针。行为未定义。
解决办法:要么修改原来的字符串,要么新建一个字符串对象。确保字符串对象至少在使用字符指针时存在。示例:
string dbFile = "data.db";
auto temporaryFileName = "~" + dbFile;
cout << temporaryFileName.c_str() << endl;