在C++中使用 s 后缀的任何优点

Any advantage of using the s suffix in C++

本文关键字:后缀 任何优 C++      更新时间:2023-10-16

我的问题与C++中使用"s"后缀有关?

使用"s"后缀的代码示例:

auto hello = "Hello!"s; // a std::string

同样可以写成:

auto hello = std::string{"Hello!"};

我能够在网上找到应该使用"s"后缀来最小化错误并澄清我们在代码中的意图。

因此,使用"s"后缀是否仅适用于代码的读者?还是使用它还有其他优点?

空字符可以简单地包含在原始字符串中; http://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s 的例子

int main()
{
    using namespace std::string_literals;
    std::string s1 = "abcdef";
    std::string s2 = "abcdef"s;
    std::cout << "s1: " << s1.size() << " "" << s1 << ""n";
    std::cout << "s2: " << s2.size() << " "" << s2 << ""n";
}

可能的输出:

s1: 3 "abc"
s2: 8 "abc^@^@def"

因此,使用"s"后缀是否仅适用于代码的读者?

不,它不仅适用于代码的读者,而且告诉编译器要从文字创建哪种确切类型。

还是使用它还有其他优点?

当然:编写更短的代码但产生所需的类型是有好处的

auto hello = "Hello!"s;

正如您所注意到的,这会产生一个std::string并且与写作相同

auto hello = std::string{"Hello!"};

auto hello = "Hello!";

将创建一个指向const char[7]数组的const char*指针。