网站开发的前端语言是哪些南京网站排名提升
auto 自动推导的规则很多、很细,当涉及移动语义、模板等复杂的规则时,很容易绕进去。因此,在使用 auto 进行自动推导时,牢记以下几点:
- auto 推导出的是 “值类型”,不会是 “引用类型”。
- auto 可以和 const、& 这些类型修饰符结合,得到新的类型;在自动推导时,先不考虑额外的修饰,看看推导出的是什么类型,然后再加上修饰符。
- 类成员变量初始化时,不允许使用 auto 推到类型。
普通类型推导
auto p = new int(20); // p 的类型为 int*auto str1 = "hello"; // str1 的类型C风格字符串 const char*,至于为什么是const,很好理解,"hello" 是字面值即常量auto str2 = "hello"s; // str2 的类型为 string,需要打开名字空间 using namespace std::literals::string_literals(C++14及之后)auto str3 = std::string("hello");auto r = &str2; // string*auto i = 1; // intauto l = 2L; // longauto ll = 3LL; // long longauto f = 1.23f; // floatauto d = 3.1415926535; // doubleauto vec_init = {1, 2, 3, 4, 5}; // std::initializer_list<int>auto vec = std::vector<int>{1, 2, 3, 4, 5}; // std::initializer_list<int>
}
和 const、volatile、*、& 结合
与 const 结合
const auto i = 10; // const int
const auto f = 0.23f; // const float
const auto d = 1.234345; // const doubleconst auto s = std::string("hello"); // const stringconst auto vec_init = {1, 2, 3, 4, 5}; // std::initializer_list<int>
const auto vec = std::vector<int>{1, 2, 3, 4, 5}; // std::initializer_list<int>auto ch = "hello"; // const char *
const auto chr = "hello"; // const char *const
一个需要注意的点是,当使用字符串字面值推导时,推导出的时 const char * ,而当与 const 结合时,推导出的是 const char *const
与 & 结合
auto 根据表达式的结果推导变量类型,推导的是值类型。因此若希望推导的是引用类型,则需要和 & 结合。
auto i = 10; // int
auto &ri = i; // int&auto &r = 10; // 错误,r被推导出 int&,而左值引用不能绑定右值auto &&r = 10; // 正确,rr被推导出 int&&,右值引用只能绑定右值
int getInt() {int num = 1;return num;
}auto i = getInt(); // int
auto &r = getInt(); // 错误,getInt()返回的是将亡对象,是右值
auto &&rr = getInt(); // 正确,int&&,右值引用绑定到右值
待补充。。。(2023年10月23日)