Rpe*_*soa 9 c++ stdstring auto c++17
我的问题与在C++中使用"s"后缀有关?
使用"s"后缀的代码示例:
auto hello = "Hello!"s; // a std::string
Run Code Online (Sandbox Code Playgroud)
同样可以写成:
auto hello = std::string{"Hello!"};
Run Code Online (Sandbox Code Playgroud)
我能够在网上找到"s"后缀应该用于最小化错误并澄清我们在代码中的意图.
因此,使用"s"后缀仅仅是为了代码的读者?或者还有其他优势吗?
UKM*_*key 17
空字符可以简单地包含在原始字符串中; 例如来自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";
}
Run Code Online (Sandbox Code Playgroud)
可能的输出:
s1: 3 "abc"
s2: 8 "abc^@^@def"
Run Code Online (Sandbox Code Playgroud)
小智 5
因此,使用"s"后缀仅仅是为了代码的读者?
不,它不仅适用于代码的读者,而且告诉commpiler从文字中创建哪种确切的类型.
或者还有其他优势吗?
当然:将代码写得更短但却产生所需类型是有好处的
auto hello = "Hello!"s;
Run Code Online (Sandbox Code Playgroud)
正如你所注意到的,这创造了一个std::string和写作一样的东西
auto hello = std::string{"Hello!"};
Run Code Online (Sandbox Code Playgroud)
,而
auto hello = "Hello!";
Run Code Online (Sandbox Code Playgroud)
会创建一个const char*指向const char[7]数组的指针.
| 归档时间: |
|
| 查看次数: |
2597 次 |
| 最近记录: |