c++ - 在现代 C++ 中初始化字符串的方式是否有所不同?
问题描述
有区别还是只是偏好问题?我是 C++ 的初学者,我不确定自己是否选择了正确的方法来初始化字符串值,这让我很困扰。
如果我只选择一种适用于绝大多数用例的方法,会是哪一种?
// Initializing from a literal.
std::string s1{"hello"};
std::string s2("there");
std::string s3 = {"what"};
std::string s4 = "is";
// Initializing from another string object.
std::string s5{s1};
std::string s6(s1);
std::string s7 = s1;
std::string s8 = {s1};
PS:抱歉,如果之前已经提出过这个问题的全部内容,我无法在任何地方找到它,如果有人可以在这里链接到它,我将不胜感激。
解决方案
特别是对于字符串,您将始终能够使用上述所有内容,这实际上只是个人喜好问题。
我个人更喜欢
auto s1 = std::string(); //Initialize empty string
auto s2 = std::string("Hello, world"); // Initialize string containing "Hello, world"
auto s3 = s2; //Make a copy of s2
auto s4 = std::move(s3); //Move s3 into s4
我更喜欢它的原因是它适用于所有类型。如果你使用 auto,你不能忘记初始化一些东西:
int i; //Oops, forgot to initialize i, because i is a primitive
相对:
auto i = 0; //i set to 0
auto i2 = size_t(0); //i2 is a size, and set to 0
auto i3; //Error: forgot to initialize
重要的是在整个代码库中保持一致。
推荐阅读
- python - 根据不同的列表循环浏览列表?
- python - Python 3.8.8 的 TensorFlow 2.5 导入错误
- python - python中用于非常量元素的最佳数据结构
- angular - 对于某些用户而言,不再有效属性的原理图失败,但对于其他用户则没有
- javascript - JS 使用两个 TD 位信息创建新的子 TR
- python - 正则表达式在表达式中查找变量
- mysql - INNER JOIN 求和时只选择第一行 MYSQL
- angular - 在 Angular 中为相对图像 url 加上服务器 url 前缀
- javascript - 如何在 JavaScript 中多次调用相同的可链接函数
- python - 十六进制到二进制问题