QString 到 std::string 到 const char* 的转换在赋值中不起作用
QString to std::string to const char* conversion does not work in assignment
此代码:
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;
打印:
A: TEST1
A: TEST1
B: TEST2
B: B:
我不知道上次cout
发生了什么。 (显然我可以直接打印 std::string
,但这段代码是我需要 C 风格字符串的更大项目的示例)
在写问题的过程中,我发现了一个小错误:在这一行之后
const char* b_c = b.toStdString().c_str();
b.toStdString()
返回的std::string
不存在了,所以调用了析构函数,b_c
指针不再有效。相反,
std::string("B: ") + b.toStdString().c_str();
将连接的值复制到新字符串中,因此 b.toStdString()
的无效不再是问题。
显然 a_c
不是问题,因为 a
永远不会被销毁。
此代码:
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;
打印:
A: TEST1
A: TEST1
B: TEST2
B: B:
我不知道上次cout
发生了什么。 (显然我可以直接打印 std::string
,但这段代码是我需要 C 风格字符串的更大项目的示例)
在写问题的过程中,我发现了一个小错误:在这一行之后
const char* b_c = b.toStdString().c_str();
b.toStdString()
返回的std::string
不存在了,所以调用了析构函数,b_c
指针不再有效。相反,
std::string("B: ") + b.toStdString().c_str();
将连接的值复制到新字符串中,因此 b.toStdString()
的无效不再是问题。
显然 a_c
不是问题,因为 a
永远不会被销毁。