Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between const char * and literal string?

Tags:

c++

qt

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?

like image 579
Maverick33 Avatar asked Dec 27 '22 03:12

Maverick33


1 Answers

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.


When you call
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.)

like image 166
BoBTFish Avatar answered Dec 29 '22 06:12

BoBTFish