The use of the new C + + 11 feature Auto

Source: Internet
Author: User

Static types, dynamic types, and type derivation

In programming language classifications, C/c++c is often considered a static type of language. And some programming languages are called "dynamic types," such as Python. In general, the difference between "static" and "moving" is very intuitive. Let's take a look at this simple Python code:

  Name= ' world\n '  print ' Hello, '%name

The implementation of a hellowworld in Python in this piece of code. This is the "dynamic type" in the programming language, where type checking is performed at run time, while type checking in C + + is in the compile phase. Dynamic type language can be determined at run time, mainly due to a technology, which is type derivation.

In fact, type inference can also be used in statically typed languages. For example, in the Python code above, the world\n expression should be able to return a temporary string in the way that the C + + programmer thinks, so even if name is not declared, we can easily deduce that the type of name should be a string type. In C++11, the idea was realized. One of the implementations of type deduction in C++11 is to redefine the Auto keyword, and another implementation is decltype.

We can use the C++11 method to write the Python code just now.

#include <iostream>using namespace Std;int main () {  auto name= ' world\n '  cout<< ' Hello   ' < <name<<endl;}
Here, the Auto keyword is used to require the compiler to automatically derive the type of the variable name. Here the compiler infers the type of name as char*, depending on the type of its initialization expression. In fact, the Atuo keyword has a completely different meaning in the early C + + standard. When declaring a variable that uses auto modifiers, it is a local variable with an automatic storage period, as explained by the earlier C + + standard. But that's the case. The keyword is almost no use, because a variable that is not declared as static within a general function always has a local variable with an automatic storage period. Auto declares that the type of the variable must be deduced by the compiler at compile time.

Use the following example to understand the basic usage of the following auto type deduction

#include <iostream>using namespace Std;int main () {     double foo (); auto x=1; auto Y=foo (); struct m {     int i;} Str Auto Str1=str; Auto Z; Z=x;}

The above variable x is initialized to 1 because the literal variable 1 is of type const int, so the compiler infers that the type of x should be int (here the const type limiter is removed, which is explained later). Similarly, in the definition of the variable y, the y of the auto type is deduced as a double type, whereas in the definition of auto str1, its type is deduced as struct m. Here Z, declared with the Auto keyword, but not immediately defined, the compiler will error. This is different from the use rules for variables that are declared after the other keyword (except for the keyword that references the type). The variable that auto declares must be initialized so that the compiler can derive its type from its initialization expression. In this sense, auto is not a type declaration, but rather a "placeholder" when a type is declared, and the compiler is already pro to replace Suto with the actual type of the variable.

Second, the advantages of auto

1. Intuitively, one of the biggest advantages of auto derivation is simplifying code when you have a complex type variable declaration with an initialization expression. Because of the development of C + +, variable types become more and more complex. But many times, namespaces and templates become part of the genre, causing programmers to tread on thin ice when using libraries.

#include <string> #include <vector>void loopover (std::vector<std::string>&vs) {    std:: Vector<std::string>::iterator I=vs.begin (); for (; I<vs.end (); i++) {}}
Using Std::vector<std::string>::iterator to define I is a good habit commonly used by C + +, but such a long declaration brings difficulty in code readability, so by introducing auto, you increase the readability of your code. And it will be easier to use STL
<pre name= "code" class= "CPP" > #include <string> #include <vector>void loopover (std::vector<std:: String>&vs) {for (  auto I=vs.begin ();; I<vs.end (); i++) {}}

2. You can avoid the hassle of type declarations and avoid errors when type declarations are made. In fact, there are a lot of implicit or user-defined conversion rules in C + + (for example, when an integer is an addition to a character type, an expression returns an integral type, which is an implicit rule). These rules are not easy to remember, especially after the user has customized many operators, this time auto has the user's place. Take a look at the example

Class pi{public   :          double operator* (float v)  {     return (double) val*v;  }          const float val=3.1415927f;}
int main () {          float radius=1.7e10;  Pi Pi;  Auto circumference =2* (Pi*radius);}
The above defines a variable radius (radius) of type float and a variable pi for a custom type pi, using the auto type to define the variable circumference when calculating the perimeter. The pi here is the value of double when the float type data is multiplied. The PI definition may be in other places (in the header file), the main function of the program may not know the Pi author in order to avoid data overflow or the accuracy of the reduction of the return of the double type of floating-point number. Therefore, if the main function programmer uses the float type to declare circumference, it may not be able to enjoy the benefits of the PI author's careful design. Conversely, it is no problem to declare circumference as auto, because the compiler has made the best choice.

But auto doesn't solve all the accuracy problems. The following example

#include <iostream>using namespace Std;int main () {   unsigned int a=4294967295;//the largest unsigned int value   unsigned int b=1;   auto c=a+b;   cout<< "A=" <<a<<endl;   cout<< "b=" <<b<<endl;   cout<< "c=" <<C<<ENDL;}
In the above code, the programmer wants to solve the a+b overflow problem by declaring the variable C as auto. In fact, since A+b return is still the value of unsigned int, the type of C is still deduced as unsigned int,auto can not be helpful. This is not the same as the automatic extension of data hi in the dynamic type language.

3. In C + +, its "adaptive" capability can support generics programming to some extent.

Back to the class Pi example above, it is assumed that Pi's author changed the definition of pi, for example, the operator* return value changed to a long double, at this point, the main function does not need to be modified, because auto will be "adaptive" to the new type. Similarly, for two-generation horse maintenance on different platforms, Auto also brings some "generics" benefits. Here we have a strlen function, for example, in a 32-bit compilation environment, STRLEN returns a 4-byte integer, in a 64-bit compilation environment, STRLEN returns a 8-byte integer. Even though <cstring> in the system library provides the size_t type to support code sharing support across multiple platforms, using the Auto keyword can also achieve a cross-platform effect on the code.

Auto Var=strlen ("Hello World").

Since the applicability of size_t is often limited to functions defined in <cstring>, Auto has a significantly wider scope of application.

When auto is applied to the definition of the template, its "adaptive" will be more fully reflected. We can look at the following example

Template<typename t1,typename t2>double Sum (t1&t1,t2&t2) {        auto A=t1+t2;return A;} int main () {        int a=3;long b=5;float c=1.0f;float d=2.3f;auto e=sum<int,long> (A, B),//e type is deduced as Longauto f=sum <float,float> (c,d); the type of//s is deduced to float}
The sum template function above accepts two parameters. Because T1,T2 is to be determined when the template is instantiated, sum declares the type of the variable s as auto. In the function main, when we instantiate the template. The s variable in sum<int,long> is deduced as a long, while the s variable in sum<float,float> is deduced as float. As you can see, when auto is used with templates, its "adaptive" feature strengthens the ability to generics in C + +.

Third, the use of auto attention to detail

① we can use Valatile,pointer (*), reference (&), rvalue Reference (&&) to decorate auto

Auto k = 5;auto* PK = new auto (k); auto** PpK = new Auto (&k); const auto n = 6;

② a variable declared with auto must be initialized

Auto m; M should be intialized  

③auto cannot be combined with other types of combinations

auto int p; This is the practice of old auto.

④ function and template parameters cannot be declared as auto

void MyFunction (auto parameter) {}//No auto as Method Argumenttemplate<auto t>//utter nonsense-not allowedvoid Fun (T-t) {}

⑤ a variable defined on a heap, an expression that uses auto must be initialized

int* p = new Auto (0); fineint* pp = new auto (); should be Initializedauto x = new Auto (); Hmmm. No intializerauto* y = new auto (9); Fine. Here y is a int*auto z = new Auto (9); Fine. Here Z is a int* (It isn't just an int)

⑥ that auto is a placeholder, not a type of his own, and therefore cannot be used for type conversions or other operations such as sizeof and typeID

⑦ a variable defined in an auto sequence must always be deduced to the same type

Auto X1 = 5, x2 = 5.0, x3= ' R ';  This is too much....we cannot combine

⑧auto cannot be automatically deduced as Cv-qualifiers (constant & volatile qualifiers) unless declared as a reference type

const int i = 99;auto j = i;       j is int, rather than const INTJ = +           //Fine. As J is not constant//now let us try to have referenceauto& k = i;      Now-K is const INT&K = +;          Error. K is constant//similarly with volatile qualifer

⑨auto will degenerate exponentially pointer to array unless declared as reference

int A[9];auto j = A;cout<<typeid (j). Name () <<endl; This would print int*auto& k = A;cout<<typeid (k). Name () <<endl; This would print int [9]





The use of the new C + + 11 feature Auto

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.