如何区分C++中的char数组和字符串? char数组在哪些方面更胜于std::string?
如何区分C++中的char数组和字符串? char数组在哪些方面更胜于std::string?
使用字符数组的一个原因(我个人认为不是非常好的原因)是当你想要让你的代码能够在C编译器和C++编译器中都能够编译时。
Before C++20, std::string
could not be used in constexpr
context. So, I still prefer declaring global string constants with constexpr const char[]
if all I do is just passing them to some function. As @HolyBlackCat mentioned in the comments, C++17 std::string_view
makes this use-case obsolote too, especially with the new sv
literal:
#include <string_view>
using namespace std::literals;
//Compile-time string_view
constexpr auto str = "hello"sv;
const char*
is somewhat more universal. You can pass it to a function accepting const char*
, std::string
, or std::string_view
. The reverse requires std::string::c_str()
and it is not possible to so without copying the std::string_view
.
There is no dynamic allocation involved. Although std::string
might employ SSO, it is not guaranteed. This might be relevant for very small systems where the heap is precious and the program flash memory is more accomodating and contains the literal anyway.
Interacting with old libraries. But even then, std::string
is null-terminated too.
总的来说,我建议尽可能使用std::string_view
——对于任何非拥有字符串,包括持有字符串字面量。最重要的是,它应该替换const char*
和const std::string&
函数参数。如果你想拥有一个字符串,请使用std::string
。
string_view
的方法存在一个问题:如果您需要调用一个期望只读空终止字符串(例如第三方库)的函数,则必须复制整个查看的字符串以添加终止符,即使字符串视图的源已经有了它。这是一种浪费时间和资源的做法。 - M.Mstd::string_view
可以做非后缀基础的子字符串而不需要拷贝,而普通的只读空终止字符串则做不到。 - Quimby
constexpr
上下文中使用std::string
,因此我仍然更喜欢将全局常量声明为const char[]
,除非我需要对它们进行一些字符串操作。 - Quimby