1

I have a QDialog which has a QLineEdit and a slot connected to the QLineEdit's textChanged signal.

std::string gname;

void NewMsgDialog::nameChanged(QString str) {
    auto temp = str.toUtf8().constData();
    gname = str.toStdString();
}

In the debugger I can see that temp has a sensible content (e. g. "my text") but at the end of the function, gname's value says "<not accessible>". And really, if I use gname from another function, I get a SEGFAULT.

What could be wrong?

3 Answers 3

1

Just use gname = str.toStdString();

Sign up to request clarification or add additional context in comments.

Comments

1

Well, turns out, it was a bug of QT Creator's debugger. When not run in debug, gname was assigned a value just fine. Anyway, I got really useful tips from the other answers.

2 Comments

your initial code with the temp variable is wrong, it can only work by accident, possibly as a result of compiler optimizations
Ok remove the temp, I still see the <inaccessible> value after assignment into the std::string in a debug session in qtcreator using qt5-default v5.12.8 in Ubuntu 20.04 in Arm64. Is there a bug report I can check?
0

Your code has undefined behavior.

str.toUtf8() returns a temporary QByteArray, which you are calling constData() on to get a pointer to its char data, which you are saving to temp. But then the QByteArray goes out of scope after that assignment, leaving temp pointing to freed memory before it can be used in the std::string{temp} construction.

You don't need the temp variable. std::string has an operator= that takes a const char* as input. By assigning the return value of constData() directly to gname, the QByteArray stays in scope until after the assignment:

std::string gname; 

void NewMsgDialog::nameChanged(QString str) {
    gname = str.toUtf8().constData();
}

Even simpler, you can use str.toStdString() instead, which returns a UTF-8 encoded std::string:

std::string gname; 

NewMsgDialog::nameChanged(QString str) {
    gname = str.toStdString();
}

4 Comments

So just removing the temp variable and assigning directly to gname is the solution?
Also, I think that you can't change gname because of const in front of std::string gname;
@RemyLebeau Thanks, I updated the code with the suggestions you gave, but I still get the problem. (I updated the question with the new code.)
@sfphoton But you haven't, you still have the temp variable. That is the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.