为什么要使用C ++在C ++字符串? [英] Why use c strings in c++?

查看:166
本文介绍了为什么要使用C ++在C ++字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么好的理由++使用C字符串用C时下?我的课本使用它们在某些点的例子,我真的觉得它会更容易只使用一个std :: string的。

Is there any good reason to use C-strings in C++ nowadays? My textbook uses them in examples at some points, and I really feel like it would be easier just to use a std::string.

推荐答案

我不得不使用它们的唯一理由是与用C风格的字符串第三方库连接时。也可能有深奥的情况下,您会使用性能方面的原因C形式的字符串,但更多的,往往不是在使用C ++字符串的方法可能是更快,因为内联和专业化等。

The only reasons I've had to use them is when interfacing with 3rd party libraries that use C style strings. There might also be esoteric situations where you would use C style strings for performance reasons, but more often than not, using methods on C++ strings is probably faster due to inlining and specialization, etc.

您可以使用 c_str( ) 与排序的API时,但你应该知道,*返回的char是常量,你不应该修改通过该指针字符串的方法在许多情况下。在这些类型的情况下,你仍然可以使用矢量<&烧焦GT;相反,至少变得更容易的内存管理的好处。

You can use the c_str() method in many cases when working with those sort of APIs, but you should be aware that the char * returned is const, and you should not modify the string via that pointer. In those sort of situations, you can still use a vector<char> instead, and at least get the benefit of easier memory management.

这篇关于为什么要使用C ++在C ++字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆