一文详解C++11中auto的使用

Odessa ·
更新时间:2024-09-20
· 1717 次阅读

在C语言中,就有了auto关键字,它被当作是一个变量的存储类型修饰符,表示自动变量(局部变量)。它不能被单独使用,否则编译器会给出警告。在C++11标准中,添加了新的类型推导特性。在C ++11中,使用auto定义的变量不能使用其它类型修饰符修饰,该变量的类型由编译器根据初始化数据自动确定。

C++中类型检查是在编译阶段。动态类型语言能做到在运行时决定类型,主要归功于一技术,这技术是类型推导。在C++11中,可以通过重定义auto关键字来实现类型推导。

在C++11中,使用auto关键字可以要求编译器对变量的类型进行自动推导。

auto关键字:类型推导,从该关键字的初始化表达式中推导变量的类型。

在块作用域、命名空间作用域、for循环的初始化语句内声明变量的时候,变量的类型可以被省略,使用关键字auto来代替。

auto声明的变量必须被初始化,以使编译器能够从其初始化表达式中推导出其类型。

声明为auto的变量在编译时期就分配了内存,而不是到了运行时期,所以使用auto不再引发任何速度延迟,这也意味着使用auto的时候,这个变量不初始化会报错,因为编译器无法知道这个变量的类型。

auto使用时需注意:

(1)、可以使用const、volatile、pointer(*)、reference(&)、rvalue reference(&&)等说明符和声明符来修饰auto关键字;

(2)、用auto声明的变量必须初始化;

(3)、auto不能与其它任何类型说明符一起使用;

(4)、方法、参数或模板参数不能被声明为auto;

(5)、定义在堆上的变量,使用了auto的表达式必须被初始化;

(6)、auto是一个占位符,不是类型,不能用于类型转换或其它一些操作,如sizeof、typeid;

(7)、auto关键字内声明的声明符列表的所有符号必须解析为同一类型;

(8)、auto不能自动推导成CV-qualifiers(constant& volatile qualifiers),除非被声明为引用类型;

(9)、auto会退化成指向数组的指针,除非被声明为引用;

(10)、auto不能作为函数的返回类型,在C++14中是可以的。

建议:大多数情况使用关键字auto,除非非常需要转换。

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "auto.hpp" #include <iostream> #include <cmath> #include <typeinfo> #include <string> #include <map> #include <list> #include <deque> #include <vector> // // reference: http://en.cppreference.com/w/cpp/language/auto template<class T, class U> auto add(T t, U u) -> decltype(t + u) // the return type is the type of operator+(T, U) { return t + u; } auto get_fun(int arg) -> double(*)(double) // same as: double (*get_fun(int))(double) { switch (arg) { case 1: return std::fabs; case 2: return std::sin; default: return std::cos; } } int test_auto1() { auto a = 1 + 2; std::cout << "type of a: " << typeid(a).name() << '\n'; // type of a: int auto b = add(1, 1.2); std::cout << "type of b: " << typeid(b).name() << '\n'; // type of b: double auto c = { 1, 2 }; std::cout << "type of c: " << typeid(c).name() << '\n'; // type of c: class std::initializer_list<int> auto my_lambda = [](int x) { return x + 3; }; std::cout << "my_lambda: " << my_lambda(5) << '\n'; // my_lambda: 8 auto my_fun = get_fun(2); std::cout << "type of my_fun: " << typeid(my_fun).name() << '\n'; // type of my_fun: double (__cdecl*)(double) std::cout << "my_fun: " << my_fun(3) << '\n'; // my_fun: 0.14112 // auto int x; // error as of C++11: "auto" is no longer a storage-class specifier // error C3530: “auto”不能与任何其他类型说明符组合 return 0; } // reference: https://msdn.microsoft.com/zh-cn/library/dd293667(v=vs.120).aspx int f(int x) { return x; } int test_auto2() { int count = 10; int& countRef = count; auto myAuto = countRef; countRef = 11; std::cout << count << " " << std::endl; // 11 myAuto = 12; std::cout << count << std::endl; // 11 // 1. 下面的声明等效。 在第一个语句中,声明 j 变量为类型 int。 在第二个语句,因为初始化表达式 (0) 是整数,所以变量 k 推导为 int 类型 int j = 0; // Variable j is explicitly type int. auto k = 0; // Variable k is implicitly type int because 0 is an integer. // 2. 以下声明等效,但第二个声明比第一个简单 std::map<int, std::list<std::string>> m; std::map<int, std::list<std::string>>::iterator i = m.begin(); auto i_ = m.begin(); // 3. 声明 iter 和 elem 变量类型 std::deque<double> dqDoubleData(10, 0.1); for (auto iter = dqDoubleData.begin(); iter != dqDoubleData.end(); ++iter) { /* ... */} // prefer range-for loops with the following information in mind // (this applies to any range-for with auto, not just deque) for (auto elem : dqDoubleData) // COPIES elements, not much better than the previous examples { /* ... */ } for (auto& elem : dqDoubleData) // observes and/or modifies elements IN-PLACE { /* ... */ } for (const auto& elem : dqDoubleData) // observes elements IN-PLACE { /* ... */ } // 4. 使用 new 运算符 double x = 12.34; auto *y = new auto(x), **z = new auto(&x); // 5. 所有符号解析为同一类型 auto x_ = 1, *y_ = &x_, **z_ = &y_; // Resolves to int. auto a(2.01), *b(&a); // Resolves to double. auto c = 'a', *d(&c); // Resolves to char. auto m_ = 1, &n_ = m_; // Resolves to int. // 6. 使用条件运算符 (?:) int v1 = 100, v2 = 200; auto e = v1 > v2 ? v1 : v2; // 7. 将变量 x7 初始化类型 int,将引用的变量 y7 初始化为类型 const int,及将变量 fp 初始化为指向返回类型 int 的函数的指针 auto x7 = f(0); const auto & y7 = f(1); int(*p)(int x7); p = f; auto fp = p; return 0; } / // reference: http://www.learncpp.com/cpp-tutorial/4-8-the-auto-keyword/ int add_3(int x, int y) { return x + y; } int test_auto3() { auto d = 5.0; // 5.0 is a double literal, so d will be type double auto i = 1 + 2; // 1 + 2 evaluates to an integer, so i will be type int auto sum = add_3(5, 6); // add_3() returns an int, so sum will be type int return 0; }

GitHub:https://github.com/fengbingchun/Messy_Test

到此这篇关于一文详解C++11中auto的使用的文章就介绍到这了,更多相关C++11 auto内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



c+ c++11 C++ auto

需要 登录 后方可回复, 如果你还没有账号请 注册新账号