C++ Qt可变寿命误解

C++ Qt可变寿命误解,c++,qt,C++,Qt,我有以下工作代码: QFile file(fileName); if(!file.open(QIODevice::ReadOnly)) throw GException(GString("Failed to open file ")); QTextStream stream(&file); QString s = stream.readAll(); QByteArray source = s.toUtf8(); const char *string = source.data(); g

我有以下工作代码:

QFile file(fileName);
if(!file.open(QIODevice::ReadOnly)) throw GException(GString("Failed to open file "));
QTextStream stream(&file);

QString s = stream.readAll();
QByteArray source = s.toUtf8();
const char *string = source.data();
glShaderSource(id, 1, &string, NULL);
glCompileShader(id);
qDebug() << QString(string);
但删除QByteArray会导致字符串指向垃圾:

QString s = stream.readAll();
const char *string = s.toUtf8().data();
glShaderSource(id, 1, &string, NULL);
glCompileShader(id);
qDebug() << QString(string); // GARBAGE HERE
QString s=stream.readAll();
const char*string=s.toUtf8().data();
glShaderSource(id,1,&string,NULL);
glCompileShader(id);
qDebug()返回一个
QByteArray
,而不是指针。不将字符串存储为utf-8 C字符串:

QString存储一个16位QChar字符串,其中每个QChar对应 一个Unicode 4.0字符。(具有上述代码值的Unicode字符) 65535使用代理项对存储,即两个连续的QCHAR。)

在这方面:

const char *string = s.toUtf8().data();
您正在临时
QByteArray
上使用,但正如
data()
的文档所述:

只要不重新分配字节数组,指针就保持有效 或者被摧毁


我明白了,非常感谢。当我说“指针”时,我并不是说QByteArray是指针,而是说它包含指向内部数组的指针。不管怎样,现在我明白了根本原因
toUtf8()
执行转换,因为内部编码不是UTF-8。我没想过。
const char *string = s.toUtf8().data();