I'm new to Qt - but this may be a very basic c++ issue. I have a simple function that returns a QString:
QString testclass::myfunc(int i)
{
QString result;
switch (i) {
case 1: result = "one"; break;
case 2: result = "two"; break;
}
return result;
}
Is this safe? Does the c compiler ensure the return value stays in memory long enough to be used by the calling function? (Or does this risk memory corruption). If the latter, what is the right way to return a QString? (Does the result var have to be static? Does result have to be a member var of testclass?)
Does it matter that QString contains constants? (What id case 3 assigned result to a random string)
What if myfunc is a static method that I want to call from different threads? Would I have to pass in an extra Qstring by reference to ensure each caller gets their own variable (and return void)?
Here is the actual function (cleaned up a bit) - and note that this function is STATIC in case that makes a difference:
QString L::toString(const L::editions &level)
{
QString levelStr;
switch (level) {
case L::one:
levelStr = "one";
break;
case L::two:
levelStr = "two";
break;
case L::three:
levelStr = "thre";
break;
default:
levelStr = "Internal Error";
break;
}
return levelStr;
}
and yet valgrind complains (line 121 is 'levelStr = "one";')
34 bytes in 1 blocks are definitely lost in loss record 197 of 716
in L::toString(L::edition const&) in /mnt/lserver2/data/development/haast/src/linfo.cpp:121
1: malloc in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so
2: QArrayData::allocate(unsigned long, unsigned long, unsigned long, QFlags<QArrayData::AllocationOption>) in /opt/Qt/5.3/gcc_64/lib/libQt5Core.so.5.3.1
3: QString::QString(int, Qt::Initialization) in /opt/Qt/5.3/gcc_64/lib/libQt5Core.so.5.3.1
4: /opt/Qt/5.3/gcc_64/lib/libQt5Core.so.5.3.1
5: QString::fromUtf8_helper(char const*, int) in /opt/Qt/5.3/gcc_64/lib/libQt5Core.so.5.3.1
6: QString::fromUtf8(char const*, int) in <a href="file:///opt/Qt/5.3/gcc_64/include/QtCore/qstring.h:492" >/opt/Qt/5.3/gcc_64/include/QtCore/qstring.h:492</a>
7: QString::operator=(char const*) in <a href="file:///opt/Qt/5.3/gcc_64/include/QtCore/qstring.h:609" >/opt/Qt/5.3/gcc_64/include/QtCore/qstring.h:609</a>
8: L::toString(L::Lconst&) in <a