MFC:std::string vs CString?

2022-01-12 00:00:00 string c++ mfc stdstring cstring

在 MFC 中使用 C++.来自 C# 背景,我通常只对所有字符串使用字符串.我将它们用于类成员、方法参数和方法返回值.

Using C++ with MFC. Coming from a C# background I typically just use string for all, well, strings. I use them for class members, method parameters, and method return values.

现在在 C++ 中,我有 std::string、CString、char *、LPCTSTR 等等.当我设计我的数据成员、方法参数和方法返回值时,我应该使用哪种类型?易用性很重要,CString 似乎提供了这一点,但我的直觉是倾向于可移植标准,尽管可移植性在我的优先级列表中非常低(现在).另外,我不喜欢创建字符串缓冲区并将它们传递给方法和函数的 c 语义.

Now in C++ I've got std::string, CString, char *, LPCTSTR, and more. As I design my data members, method parameters, and method return values which type(s) should I be using? Ease of use is important and CString seems to offer that but my instinct is toward portable standards although portability is pretty low on my list of priorities (now). Also, I don't like the c semantics of creating string buffers and passing them into methods and functions.

我认为从直接易于编码的角度来看,CStrings 可能具有优势.但是,总的来说,什么是高代码质量"的方式来做到这一点?

I think from an immediate ease of coding perspective CStrings probably have the edge. But, overall, what is the "high code quality" way to do this?

我特别关心代码中的接口点(即方法参数和返回值).例如:

I'm especially concerned about the interface points in my code (i.e. method parameters and return values). E.g.:

Shape::SetCaption(const char *caption) {...}

Shape::SetCaption(CString caption) {...}

Shape::SetCaption(std::string caption) {...}

Shape::SetCaption(std::wstring caption) {...}

推荐答案

我通常更喜欢让我的编码风格适应我正在工作的框架,以与之保持一致.因此,当我使用 MFC 时(我已经很久没有使用它了),我更喜欢使用 CString (和 LPCTSTR 作为公共接口方法中的函数参数).在使用 Qt 时,我更喜欢 QString 和 Qt 的容器而不是 STL 容器,对于与此类框架不直接相关的所有内容,我使用 std::string 因为它是标准的 C++ 方式处理字符串.

I usually prefer to adapt my coding style to the framework I'm working in to be consistent with it. So when I work with MFC (which i haven't for a long time), I prefer the use of CString (and LPCTSTR as function arguments in public interface methods). When working with Qt I prefer QString and Qt's containers over STL containers and for everything not directly related to such a framework I use std::string as it's the standard C++ way of handling strings.

这并没有太大的区别,因为它们都提供或多或少相同的功能(并且很容易相互转换),并且当为某个框架编写代码时,无论如何它都取决于它,因此可移植性是不是那么大的问题.

It doesn't make such a huge difference, since they all offer more or less equal functionality (and are easily convertible into each other) and when code is written for a certain framework, it depends on it anyway, so portability is not such a huge concern.

只是不要为普通的 char 数组而烦恼!顺便说一句,尝试通过 const 引用 (const std::string &caption) 而不是按值传递对象,因为在 C++ 中,变量不会自动引用,复制字符串会变得非常昂贵.

Just don't bother with plain char arrays! And by the way, try to pass objects by const reference (const std::string &caption) and not by value, as in C++ variables are not automatically references and copying a string can get quite expensive.

相关文章