我想将字面符号“〜”与字符串变量连接起来。
string dbFile = "data.db";
const char *temporaryFileName = ("~" + dbFile).c_str(); // it must be ~data.db
cout << temporaryFileName << endl;
没有错误,但是在打印时,什么都没有出来,为什么?
答案 0 :(得分:1)
查看您使用的运算符的返回类型:
string operator+(const char* lhs, string& rhs); // untempletized for simplicity
特别注意它返回一个新对象。因此,表达式("~" + dbFile)
返回一个新的临时对象。临时对象仅存在于完整表达式语句之前(除非由引用绑定)。在这种情况下,语句以同一行的分号结束。
只有指向的c_str()
对象仍然存在,才允许使用string
返回的指针。您使用字符串不再存在的下一行上的指针。行为未定义。
解决方案:修改原始字符串,或创建新的字符串对象。确保字符串对象至少与使用字符指针一样长。例如:
string dbFile = "data.db";
auto temporaryFileName = "~" + dbFile;
cout << temporaryFileName.c_str() << endl;