views:

49

answers:

2

I am using a 3rd party library with Qt that requires char* strings. I am using the following code to convert my QString to a char*

char* toCharArray(const QString &string)
{
    QByteArray bytes = string.toLocal8Bit();
    char* data = new char[bytes.count() + 1];
    strcpy(data, bytes.data());
    return data;
}

// later on...

3rdPartyObject->3rdPartyMethod(toCharArray("someFile"));

What can I do to make sure the char* I return is cleaned up, apart from doing something messy like this?

char* path = toCharArray("someFile");
3rdPartyObject->3rdPartyMethod(path); // The class and method called can differ
delete[] path;
A: 

You can use a smart pointer such as boost::shared_ptr or std::auto_ptr so that the memory is automatically deleted when the smart pointer goes out of scope.

Naveen
+6  A: 

Why not just use

QString s;
3rdPartyObject->3rdPartyMethod( s.toLocal8Bit().data() );

The destruction of the temporary QByteArray at the end of the statement will clean up all the resources.

Michael Anderson
Thanks. This actually does work... something I read elsewhere led me to believe it would not. Guess I should stay on Stack Overflow. :)
Jake Petroules
even better: use constData() where possible (where the function takes const char*). Saves the extra detach (data() might copy the data unnecessarily internally)
Frank
@Frank - absolutely. I was just matching the OPs required type, +1
Michael Anderson
@Frank I did. ;) `const` isn't part of the actual data type so I didn't include it in my question since it wasn't relevant. +1 for any Googlers that see your comment, though.
Jake Petroules
Just for the sake of completeness, 'elsewhere' refers to the official Qt docs: http://developer.qt.nokia.com/faq/answer/how_can_i_convert_a_qstring_to_char_and_vice_versa, which say "`const char *c_str2 = str2.toLatin1().data();` will make the application crash as the QByteArray has not been stored and hence no longer exists"... I wasn't thinking and should have known this *would* work in my particular situation based on the rules of C++...
Jake Petroules