Search code examples
c++qstring

QString to std::string to const char* conversion does not work in assignment


This code:

std::string a("TEST1");
const char* a_c = a.c_str();
QString b("TEST2");
const char* b_c = b.toStdString().c_str();

std::string s1 = std::string("A: ") + a.c_str();
std::string s2 = std::string("A: ") + a_c;
std::string s3 = std::string("B: ") + b.toStdString().c_str();
std::string s4 = std::string("B: ") + b_c;

std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
std::cout << s3 << std::endl;
std::cout << s4 << std::endl;

prints:

A: TEST1
A: TEST1
B: TEST2
B: B: 

I don't know what's happened on the last cout. (Obviously I can print directly the std::string, but this piece of code is an example on a bigger project where I need the C-style string)


Solution

  • During writing the question I found the trivial bug: after this line

    const char* b_c = b.toStdString().c_str();
    

    the std::string returned by b.toStdString() no longer exists, so the destructor was called and the b_c pointer is no more valid. Instead, the

    std::string("B: ") + b.toStdString().c_str();
    

    copy into the new string the value of the concatenation, so the invalidation of b.toStdString() is no more a problem.

    Obviously a_c is not a problem because a is never destroyed.