C++Guns – RoboBlog


QString to std::string (Bug of the day 8)

Filed under: Allgemein — Tags: , — Thomas @ 11:06
std::string class::func() const noexcept {
    return name.toLatin1().constData();

3 convertions. From QString to QByteArray to const char* to std::string. Lets see if it works. From Qt Docu

const char * QByteArray::?constData() const
Returns a pointer to the data stored in the byte array. The pointer can be used to access the bytes that compose the array. The data is '\0'-terminated unless the QByteArray object was created from raw data.

basic_string( const CharT* s, const Allocator& alloc = Allocator() )
Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if s does not point at an array of at least Traits::length(s)+1 elements of CharT.

Okay this should work, but can fail.

Using Qt function to convert QString to std::string is the better solution:

std::string QString::toStdString() const

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress