I'm working on a form which has QT widget, I have to set some value in a QTextEdit field. I had to call a function which is declared like :
void SDB::setDescription(const char *Description);
and when I call it by this method (i)
const char * desc = saveOptionsDesLineEditBox->text().toStdString().c_str();
SDB::setDescription(desc);
It shows unrecognised symbol in the widget's text box. but by calling by this second method (ii)
SDB::setDescription(saveOptionsDesLineEditBox->text().toStdString().c_str());
works fine. Why there is difference between these two methods?
The std::string
returned by saveOptionsDesLineEditBox->text().toStdString()
is a temporary. It goes out of scope at the end of the line, and is destroyed, along with its contents. Therefore, referring to the contained const char*
returned by c_str()
through desc
in the next line is undefined behaviour.
SDB::setDescription(saveOptionsDesLineEditBox->text().toStdString().c_str());
all in the same statement, the temporary exists for long enough that setDescription
can read and copy the c string safely.
I'd suggest something along the lines of
std::string desc = saveOptionsDesLineEditBox->text().toStdString();
SDB::setDescription(desc.c_str());
Strictly speaking this will incur one copy more than necessary (or a move if you have c++11
), but who really cares here. Making the code simpler to understand is a good thing in its own right.
(Note, this is a guess, not having seen any of the function signatures, but it is pretty likely a good one.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With