首页 > 解决方案 > 在现代 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:抱歉,如果之前已经提出过这个问题的全部内容,我无法在任何地方找到它,如果有人可以在这里链接到它,我将不胜感激。

标签: c++

解决方案


特别是对于字符串,您将始终能够使用上述所有内容,这实际上只是个人喜好问题。

我个人更喜欢

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

重要的是在整个代码库中保持一致。


推荐阅读