互换使用 std::string 和 QString
我在我正在开发的图形和 GUI 组件软件系统中广泛使用 Qt。然而,对于大多数内部算法和数据处理来说,Qt 发挥的作用较小。
我经常会遇到从 std::string 转换为 QString 的需要,反之亦然。我的倾向是尽可能多地使用 std::string ,并且当我需要将字符串传递给 Qt 类(例如使用文件系统的类)时,仅使用 QString 。
当我今天早上编程时,我突然意识到,在我的代码中同时使用 std::string 和 QString 可能是一个糟糕的设计。我应该完全切换到 QString 吗?还有其他人遇到过这种设计选择吗?
Qt 提供了许多与 STL 相同的功能,但我仍然犹豫是否要完全切换,因为 Qt 的标准化和稳定性较差。
I use Qt extensively in a software system I'm working on for graphical and GUI components. However, for most internal algorithms and processing of data Qt plays a smaller role.
I'll often run into the need to convert from std::string to QString or visa versa. My inclination is to use std::string as much as possible and use QString only when I need to pass strings to Qt classes like those that work with the file system.
As I was programming this morning, it hit me that it may be bad design to have both std::string and QString sprinkled throughout my code. Should I completely switch to QString? Has anyone else run into this design choice?
Qt provides a lot of the same functionality of STL, but I'm still hesitant switching completely since Qt is less standardized and stable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,我以前也遇到过这种情况。我开发的程序自始至终都使用 Qt,但我必须将其连接到需要
std::string
的库。QString
的好处是它显式使用 Unicode,而 C++ 标准库对编码不做任何保证。解决方案是在该库的边界处进行转换,
因为该库生成了包含 UTF-8 的
std::string
。您似乎想要的恰恰相反:始终使用
std::string
并在 Qt 边界进行转换。看起来完全没问题;它比总是使用QString
需要更多的工作,但是当您需要一个不接受QString
的库时,您必须付出努力,并且您的非- GUI 组件不依赖于 Qt(万岁!)。Yes, I've had this situation before. The program I worked on used Qt throughout, but I had to hook it up to a library that expected
std::string
. The benefit ofQString
is that it explicitly uses Unicode, while the C++ standard library makes no guarantees about encoding.The solution was to convert at the boundary of this library with
since the library produced
std::string
's containing UTF-8.What you seem to want is the exact opposite: use
std::string
throughout and convert at the Qt boundary. That seems perfectly ok; it takes a bit more work than always usingQString
, but you'll have to put in effort when you need a non-QString
-accepting library anyway, and your non-GUI components don't depend on Qt (hurrah!).我会说在你的程序核心中使用
std::string
,并在你处理GUI部分时将它们转换为QString
。如果你想改变你的 GUI 工具包,那会更容易。I would say use
std::string
in your program core, and convert them toQString
when your are working on GUI part. I you ever want to change your GUI toolkit, that will be easier.