Any advantage of using s suffix in C ++

My question is related to using s suffix in C ++?

Sample code using the suffix "s":

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

The same can be written like this:

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

I was able to find on the Internet that the suffix "s" should be used to minimize errors and to clarify our intentions in the code.

Therefore, is the suffix "s" read-only? Or are there other benefits to using it?

+9
c ++ stdstring auto c ++ 17
source share
2 answers

Zero characters can be trivially included in the source string; 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" 
+17
source share

Therefore, is the use of the suffix "s" intended only for the code reader?

No, this is not only for the code reader, but also tells the compiler which type to create from the literal.

Or are there other benefits to using it?

Of course: there is an advantage in writing this code shorter, but at the same time get the type you are looking for

 auto hello = "Hello!"s; 

As you noticed, this creates a std::string and is similar to writing

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

whereas

 auto hello = "Hello!"; 

will create a const char* pointer pointing to a const char[7] array.

+5
source share

All Articles