简体   繁体   English

文字符号和字符串变量之间的串联,然后返回const char *

[英]A concatenation between a literal symbol and a string variable then return const char*

I want to concatenate a literal symbol "~" with a string variable. 我想将文字符号“〜”与字符串变量连接在一起。

string dbFile = "data.db";
const char *temporaryFileName = ("~" + dbFile).c_str();  // it must be ~data.db
cout << temporaryFileName << endl;

No errors, but when printing, nothing comes out, why? 没有错误,但是在打印时什么也没出来,为什么?

Take a look at the return type of the operator that you use: 查看您使用的运算符的返回类型:

string operator+(const char* lhs, string& rhs); // untempletized for simplicity

Note in particular that it returns a new object. 特别注意,它返回一个新对象。 As such, the expression ("~" + dbFile) returns a new temporary object. 这样,表达式("~" + dbFile)返回一个新的临时对象。 Temporary objects exist only until the full expression statement (unless bound by a reference). 临时对象仅在完整的表达式语句之前存在(除非受引用约束)。 In this case, the statement ends at the semicolon on that same line. 在这种情况下,该语句在同一行的分号处结束。

Using the pointer returned by c_str() is allowed only as long as the pointed string object still exists. 仅在指向的string对象仍然存在的情况下,才允许使用c_str()返回的指针。 You use the pointer on the next line where the string no longer exists. 您可以在下一个不再存在字符串的行上使用指针。 The behaviour is undefined. 该行为是不确定的。

A solution: Either modify the original string, or create a new string object. 解决方案:修改原始字符串,或创建一个新的字符串对象。 Make sure that the string object exists at least as long as the character pointer is used. 确保字符串对象至少与使用字符指针的时间相同。 Example: 例:

string dbFile = "data.db";
auto temporaryFileName = "~" + dbFile;
cout << temporaryFileName.c_str() << endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM