[英]QString to std::string to const char* conversion does not work in assignment
This code: 这段代码:
std::string a("TEST1");
const char* a_c = a.c_str();
QString b("TEST2");
const char* b_c = b.toStdString().c_str();
std::string s1 = std::string("A: ") + a.c_str();
std::string s2 = std::string("A: ") + a_c;
std::string s3 = std::string("B: ") + b.toStdString().c_str();
std::string s4 = std::string("B: ") + b_c;
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
std::cout << s3 << std::endl;
std::cout << s4 << std::endl;
prints: 打印:
A: TEST1
A: TEST1
B: TEST2
B: B:
I don't know what's happened on the last cout
. 我不知道最后一cout
发生了什么。 (Obviously I can print directly the std::string
, but this piece of code is an example on a bigger project where I need the C-style string) (显然,我可以直接打印std::string
,但是这段代码是一个较大的项目(需要C样式的字符串)的示例)
During writing the question I found the trivial bug: after this line 在编写问题时,我发现了一个琐碎的错误:在此行之后
const char* b_c = b.toStdString().c_str();
the std::string
returned by b.toStdString()
no longer exists, so the destructor was called and the b_c
pointer is no more valid. b.toStdString()
返回的std::string
不再存在,因此调用了析构函数,并且b_c
指针不再有效。 Instead, the 相反,
std::string("B: ") + b.toStdString().c_str();
copy into the new string the value of the concatenation, so the invalidation of b.toStdString()
is no more a problem. 将串联的值复制到新字符串中,因此b.toStdString()
的无效不再是问题。
Obviously a_c
is not a problem because a
is never destroyed. 显然, a_c
不是问题,因为a
不会被破坏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.