[Qt-interest] howto convert QString to char*
Thiago Macieira
thiago at kde.org
Thu Jul 15 16:05:12 CEST 2010
On Thursday 15 July 2010 14:27:35 Andrew Hodgkinson wrote:
> Thus, the above code becomes very clumsy:
>
> char * cStr1 = qStringCopy( someQString );
> char * cStr2 = qStringCopy( anotherString );
> char * cStr3 = qStringCopy( thirdString );
>
> if ( cStr1 ) someCStringHandler( cStr1 );
> else // Handle allocation failure
>
> if ( cStr2 ) someOtherFunction( cStr2 );
> else // Handle allocation failure
>
> if ( cStr3 ) aThirdFunction( cStr3 );
> else // Handle allocation failure
>
> free( cStr1 );
> free( cStr2 );
> free( cStr3 );
Well, we're in C++ world here, since we're talking about QString. So we can
easily use a class that stores the pointers and ensures that they get freed
when the objects go out of scope.
Something like:
class CharStar
{
char *ptr;
public:
CharStarHolder(char *ptr = 0) : ptr(ptr) {}
~CharStarHolder() { free(ptr); }
operator char *() { return ptr; }
operator const char *() const { return ptr; }
};
This would certainly solve your problems above.
And, tell you what, I'll add such a class to Qt to make your life easier. I'll
also add some functions to QString to return this new class with the data that
it allocated, so you don't have to worry about creating the object.
To avoid multiple allocations, let's make it implicitly-shared too.
And QByteArray is born.
--
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
Senior Product Manager - Nokia, Qt Development Frameworks
PGP/GPG: 0x6EF45358; fingerprint:
E067 918B B660 DBD1 105C 966C 33F5 F005 6EF4 5358
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100715/c05d311b/attachment.bin
More information about the Qt-interest-old
mailing list