Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

advantage of QString over std::string

What advantages does QString offer over std::string? Can a normal std::string store unicode characters ? I m trying to write a program that will open various song files . The name of these files can be in different languages. I have heard that using a normal string in such cases will not work properly. I want to keep the application independent of QT and reuse the code for example in android . What do you suggest .

like image 907
Vihaan Verma Avatar asked Jun 14 '12 07:06

Vihaan Verma


People also ask

What is the difference between std::string and string?

There is no functionality difference between string and std::string because they're the same type.

Why do we use std::string?

std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.

What is a QString?

QString stores unicode strings. By definition, since QString stores unicode, a QString knows what characters it's contents represent. This is in contrast to a C-style string (char*) that has no knowledge of encoding by itself.

Is std::string good?

In general you should always use std::string, since it is less bug prone. Be aware, that memory overhead of std::string is significant. Recently I've performed some experiments about std::string overhead. In general it is about 48 bytes!


2 Answers

QString allows you to work with Unicode, has more useful methods and integrates with Qt well. It also has better performance, as cbamber85 noted.

std::string just stores the bytes as you give them to it, it doesn't know anything about encodings. It uses one byte per character, but it's not enough for all the languages in the world. The best way to store your texts would probably be UTF-8 encoding, in which characters can take up different number of bytes, and std::string just can't handle that properly! This, for example, means that length method would return the number of bytes, not characters. And this is just the tip of an iceberg...

like image 171
Oleh Prypin Avatar answered Oct 04 '22 10:10

Oleh Prypin


If you are using Qt framework for writing your software then you are better off using QString. The simple reason being that almost all Qt functions that work on strings will accept QString. If you use std::string you might end up in situations where you will have to typecase from one to another. You should consider using std::string if your software is not using Qt at all. That will make your code more portable and not dependent on an extra framework that users will have to install to use your software.

like image 39
Pankaj Avatar answered Oct 04 '22 09:10

Pankaj