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

I am working on a form with QT widgets, I need to set some value in the QTextEdit field. I had to call a function that is declared as:

void SDB::setDescription(const char *Description); 

and when I call it with this method (i)

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

It displays an unrecognized symbol in the widget text box. but by calling this second method (ii)

 SDB::setDescription(saveOptionsDesLineEditBox->text().toStdString().c_str()); 

works great. Why is there a difference between the two methods?

+4
source share
2 answers

std::string returned by saveOptionsDesLineEditBox->text().toStdString() is 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() via desc , in the next line this behavior is undefined.


When you call
 SDB::setDescription(saveOptionsDesLineEditBox->text().toStdString().c_str()); 

all in the same expression, temporary exists long enough so that setDescription can safely read and copy the string c.

I suggest something line by line

 std::string desc = saveOptionsDesLineEditBox->text().toStdString(); SDB::setDescription(desc.c_str()); 

Strictly speaking, this will entail one copy more than necessary (or a move if you have c++11 ), but who really cares here. Making code easier to understand is a good thing in and of itself.

(Note this assumption without seeing any of the function signatures, but this is most likely a good option.)

+7
source

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

If so, this is temporary, which will be destroyed at the end of the full expression (which is the last one on the line). Before that, you set const char * from this temporary and saved it. When it is valid only as long as the string lives.

You can correct the situation as follows:

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

or just put the whole expression in a call to setDescription.

+3
source

Source: https://habr.com/ru/post/1483562/


All Articles