问题
My question is related to the use of the "s" suffix in C++?
Example of code using the "s" suffix:
auto hello = "Hello!"s; // a std::string
The same could be written as:
auto hello = std::string{"Hello!"};
I was able to find online that the "s" suffix should be used to minimizes mistakes and to clarify our intentions in the code.
Therefore, is the use of the "s" suffix only meant for the reader of the code? Or are there others advantages to its use?
回答1:
Null characters can be included in the raw string trivially; example from http://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s
int main()
{
using namespace std::string_literals;
std::string s1 = "abc\0\0def";
std::string s2 = "abc\0\0def"s;
std::cout << "s1: " << s1.size() << " \"" << s1 << "\"\n";
std::cout << "s2: " << s2.size() << " \"" << s2 << "\"\n";
}
Possible output:
s1: 3 "abc"
s2: 8 "abc^@^@def"
回答2:
Therefore, is the use of the "s" suffix only meant for the reader of the code?
No, its not only for the reader of the code, but tells the compiler which exact type to create from the literal.
Or are there others advantages to its use?
Sure: There is the advantage to write that code shorter but yet yielding the wanted type
auto hello = "Hello!"s;
As you noticed this creates a std::string
and is the same as writing
auto hello = std::string{"Hello!"};
, whereas
auto hello = "Hello!";
would create a const char*
pointer pointing to a const char[7]
array.
来源:https://stackoverflow.com/questions/48465116/any-advantage-of-using-the-s-suffix-in-c