在C++中使用 s 后缀的任何优点
Any advantage of using the s suffix in C++
我的问题与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 = "abc def";
std::string s2 = "abc def"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*
指针。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 增量运算符与后缀混淆
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何在不产生任何垃圾的情况下获得C中的像素
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- C++映射有2个键,这样任何1个键都可以用来获取值
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- RtlCaptureStackBackTrace未捕获任何帧
- 链表c++插入,所有情况都已检查,但没有任何工作
- C++模板函数,用于比较任何无符号整数和有符号整数
- Arduino millis() - millis() 怎么能等于 0 以外的任何东西?
- 尝试摆脱任何堆内存分配
- 是否有任何C++功能可以对地图进行排序?
- 打印时有二叉树问题.用户输入不打印任何内容
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 在C++行尾写一个分号或多个分号是否会改变任何内容
- C++类型特征,以查看是否可以<uint32_t>对类型"K"的任何变量调用"static_cast(k)"
- C++ 将 CIN 值存储到任何类型的数组中
- 后缀Expressrion的插图未显示任何输出
- 在C++中使用 s 后缀的任何优点