I'll quote the Qt docs again with emphasis:
The pointer remains valid as long as the byte array isn't reallocated
or destroyed.
and add some from the C++ standards:
$12.2/3- "Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception."
So, at the statement boundary of:
char *str = s.toAscii().data();
char *str = s.toAscii().data();
To copy to clipboard, switch view to plain text mode
(s is QString) the temporary QByteArray created by the toAscii() method is destroyed. Most of the time immediately subsequent access through str will appear to work because the memory has not yet been allocated elsewhere and modified. You can be sure when it does fail intermittently you will be scratching your head. If you are going to store a pointer to the char data for later use then you must control the scope of the QByteArray by making it explicit in some form (which is what was suggested).
That does not, in any way, prohibit this immediate usage:
printf("%s\n", s.toAscii().constData());
printf("%s\n", s.toAscii().constData());
To copy to clipboard, switch view to plain text mode
which is safe because the scope of the temporary QByteArray is the end of the complete statement.
Bookmarks