1

Here's some test code:

QString qstr_test("TEST");
const char *p = qstr_test.toStdString().c_str();
cout << p << endl;

Nothing is output as p is an empty string.

Here's what I got at debugging:

std::basic_string<char,std::char_traits<char>,std::allocator<char> >::c_str 
returns:    0x003bf9d4 "TEST"   

p      :    0x003bf9d4 ""

It seems p is pointing to the right location but doesn't display the right content.

Why is p empty ?

2
  • 2
    are you sure that std::string returned by toStdString() is still exists in memory when you get to cout << p << endl; line? Commented Jun 27, 2013 at 12:55
  • @Apokal Enlightened me ! Thanks ! Commented Jun 27, 2013 at 12:57

1 Answer 1

5

std::string object is temporary and is destroyed right after c_str() is completed. But std::string owns char* buffer returned by c_str() and this buffer is also destroyed. So your code is incorrect and dangerous. You need to store std::string as long as you use char* buffer:

std::string s = qstr_test.toStdString();
const char* p = s.c_str();

Also it seems pointless to create std::string just to convert it to char*. QString has better methods: toLatin1, toLocal8bit, and toUtf8. Note that returned QByteArray has the same issue that is a common source of mistakes. QByteArray also must be stored if you want to use its buffer.

QByteArray array = qstr_test.toUtf8();
const char* p = array.constData();

I think this method is better because here you specify explicitly the encoding you need to use. And toStdString result depends on QTextCodec::codecForCStrings() current value.

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

3 Comments

toAscii should not longer be used, it's removed in Qt 5. you should use toLatin1
@WoJo Nay, toUtf8() is superior.
toUtf8 is only superior if you want UTF-8.

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.