简体   繁体   中英

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

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.


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.)

I guess .toStdString() returns a std::string, not a . std::string& to some stable object.

If so, it is a temporary, that will be destroyed at the end of the full expression (that is the last ; in the line). Before that you asked a const char* from that temporary, and store it. When it is valid only as long as string lives.

You can fix the situation like this:

const auto& desc = saveOptionsDesLineEditBox->text().toStdString();
SDB::setDescription(desc.c_str());

or just put the whole expression in the setDescription call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM