之前一直在写java,最近qt做个工具写c++,想都没想出现下面的代码:
QString qs = plainTextEdit->toPlainText(); //获取QString,这一步没问题
const char* buff = qs.toUtf8().data();
qs.toUtf8()函数把字符串QString转换为字节串QByteArray类型
QByteArray::data()则返回const char*类型
结果查看buff有时候对,有时候错。
然后分开写就没问题了:
QByteArray qba = qs.toUtf8();
const char* buff = qba.data();
c++不能连续调用函数么,为啥有时候是对的。求解析下这里面的机制。
怪我咯2017-04-17 13:53:49
Check whether toUtf8 returns a temporary object. This temporary object is destroyed after calling this line. Then your buff points to a piece of memory of this temporary object, which is not legal.
When you call it separately below, qba is not destroyed until the scope it is in exits, so there is no problem.
I personally recommend using string to save this data().