PDA

View Full Version : QString to const char



TheRonin
12th February 2007, 14:01
i've looked through some of the old posts regarding this subject, and i'm still a bit confused, especially with the bit of code that i'm writing. My question is, will the way i've written this code present problems in the future or will it be ok?



//allowed to use Qt-stuff.
const char* getChars(){
QString data = QString("asdf");
return data.toUtf8().constData();
}

//not allowed to use Qt-stuff.
//called by methods not seen here that use and rely on the returned variable.
stringStruct checkChars(){
stringStruct str = getChars();
return str;
}


the stringStruct has the '=' operator overloaded to copy the data with strcpy.

In the previous threads, it's been said that the toUtf8() function returns a bytearray that dissapears immediately after it is used and that as such, there are no guarantees that the data pointed to by the const char* pointer will be intact. But shouldn't the fact that i immediately (almost) copy the data help me in this situation? Any thoughts? suggestions?

jacek
12th February 2007, 14:40
shouldn't the fact that i immediately (almost) copy the data help me in this situation?
No, it won't help you, because "data" will be destroyed when getChars() returns and you'll get a dangling pointer. No matter how fast you will copy the string, still you'll be accessing deallocated data.

Either use something like this:
const char* getChars(){
QString data = QString("asdf");
return qstrcpy( data.toUtf8().constData() );
}

stringStruct checkChars(){
stringStruct str;
str.setBuffer( getChars() );
return str;
}
or
std::string getChars(){
QString data = QString("asdf");
return std::string( data.toUtf8().constData() );
}

stringStruct checkChars(){
stringStruct str = getChars().c_str();
return str;
}
or simply:
stringStruct getChars(){
QString data = QString("asdf");
stringStruct str = data.toUtf8().constData();
return str;
}

stringStruct checkChars(){
return getChars();
}

TheRonin
12th February 2007, 14:43
very good sir, thank you.