STL 字符串类中的运算符 char*
为什么 STL 字符串类没有内置重载的 char* 运算符?他们有什么具体原因避免这样做吗?
如果有的话,那么使用带有 C 函数的 string 类将会变得更加方便。
我想知道你的看法。
Why doesn't the STL string class have an overloaded char* operator built-in? Is there any specific reason for them to avoid it?
If there was one, then using the string class with C functions would become much more convenient.
I would like to know your views.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
以下是 Josuttis STL 书中的引用:
Following is the quote from Josuttis STL book:
您应该始终避免使用强制转换运算符,因为它们往往会在代码中引入歧义,而这些歧义只能通过使用进一步的强制转换来解决,或者更糟糕的是仍然可以编译但不执行您期望的操作。 char*() 运算符会有很多问题。例如:
将在没有警告的情况下进行编译,但会破坏字符串。
const 版本是可能的,但由于必须(可能)复制字符串才能实现它,因此它会产生不希望的隐藏成本。显式的 c_str() 函数意味着您必须始终声明您确实打算使用 const char *。
You should always avoid cast operators, as they tend to introduce ambiguities into your code that can only be resolved with the use of further casts, or worse still compile but don't do what you expect. A char*() operator would have lots of problems. For example:
would compile without a warning, but clobber the string.
A const version would be possible, but as strings must (possibly) be copied in order to implement it, it would have an undesirable hidden cost. The explicit c_str() function means you must always state that you really intend to use a const char *.
字符串模板规范故意允许字符串的“断开连接”表示,其中整个字符串内容由多个块组成。这种表示形式不允许轻松转换为 char*。
然而,字符串模板还提供了 c_str 方法来达到您想要的目的:使用该方法有什么问题?
The string template specification deliberately allows for a "disconnected" representation of strings, where the entire string contents is made up of multiple chunks. Such a representation doesn't allow for easy conversion to char*.
However, the string template also provides the c_str method for precisely the purpose you want: what's wrong with using that method?
到 1998-2002 年,它已成为 C++ 论坛的热门话题。主要问题 - 零终结者。 std::?string 的规范正常允许零字符,但 char* string 不允许。
By 1998-2002 it was hot topic of c++ forums. The main problem - zero terminator. Spec of std::?string allows zero character as normal, but char* string doesn't.
您可以使用 c_str 代替:
我相信在大多数情况下您不需要 char*,并且可以更方便地使用 string 类本身。
You can use c_str instead:
I believe that in most cases you don't need the char*, and can work more conveniently with the string class itself.
如果您需要与 C 风格函数进行互操作,则使用
std::vector
/
通常更容易。它不太方便,不幸的是你不能用
std::string
进行 O(1) 交换(现在这将是一件好事)。在这方面,我更喜欢 MFC/ATL
CString
的接口,它具有更严格的性能保证,提供互操作性,并且不会将宽字符/unicode 字符串视为完全外来的(但是好吧,后者是有点特定于平台)。If you need interop with C-style functions, using a
std::vector<char>
/<wchar_t>
is often easier.It's not as convenient, and unfortunately you can't O(1)-swap it with a
std::string
(now that would be a nice thing).In that respect, I much prefer the interface of MFC/ATL
CString
which has stricter performance guarantees, provides interop, and doesn't treat wide character/unicode strings as totally foreign (but ok, the latter is somewhat platform specific).