C ++ primer plus Reading Notes (Chapter 2 and Chapter 9)

Source: Internet
Author: User

Chapter 8 function Exploration

Inline function Selection

If the Compilation Time of the function Execution Code is longer than that of the function calling mechanism, the time saved will be only a small part of the whole process. If the code execution time is short, the inline call can save most of the time for non-inline calls. In short, inline is used to define short functions that are frequently called, for example, calling a function in a loop.

Inline Function declaration is to add inline before the function prototype or definition. In general, the prototype of the function is omitted and the entire definition is placed before the function is called. In this form, the function is particularly described.

 

Reference variable

C ++ adds a composite type compared to C: reference variable. A referenced variable is an alias that defines a variable and can be seen as a disguised pointer. It is usually used in function parameters and function return values. The former makes the transmission of large data generate no copy and is more concise than pointer encoding; the latter can ensure that statements like Cin> A> B are syntactically compliant. Calculate "CIN> A" first to return a reference to CIN, then this function "CIN> A" is an alias of CIN, so you can connect to> B later.

Because of the existence of referenced variables, the function parameter passing of C ++ is not completely passed by value, but by reference, when the parameter declaration of a function is a reference type, add const to this declaration as much as possible, because the reference alone may change the value of the original variable, and adding const will be more secure. If it is modified, errors can be found during compilation. When we pass an expression to the reference, an error is returned: The passed value is not a left value, but after adding const, we can, the compiler automatically defines an anonymous variable to save the expression and then passes the variable to the function.

The const reference variable will generate a temporary variable in two cases:

1. The real parameter type is correct, but not the left value;

2. The real parameter type is incorrect, but can be converted to the correct type.

Two anonymous structs with the same definition cannot be considered as the same variable type.

If such a function Int & FN (Int & X, int y) {return X;} is defined, such a call FN (a, B) = 3; it is equivalent to a = 3. The referenced function is actually the alias of the referenced variable.

It is very dangerous to have a function return a reference to a temporary variable. Similarly, if the referenced return value of a function can be added to a const without affecting the result, it is best to add it. Generally, you should avoid adding fuzzy features to the design because fuzzy features increase the chance of making mistakes.

If an object is declared as a constant, only common member functions can be called.

When calling a function, C ++ cannot determine whether the function prototype is referenced based on the statement that calls the function. This is also a small defect.

 

Function overload

When a function is overloaded, a major feature of C ++ exists. function matching and selection problems will occur later. C ++ allows programmers to define multiple functions with the same name, as long as the features of these functions are different (when the names are the same, the parameters are different.

A permanent method is to define a function template (parameterized types). Most of the complex library functions are implemented using templates, and the template set template is quite complex. It is precisely because of the existence of such multiple functions that the compiler will perform a reload parsing during the call to make the most suitable calls, if two or more functions are "Optimal", the compiler reports an error.

Function templates do not generate function definitions, but instead generate corresponding functions based on the type provided by the call. That is to say, the compiler helps us reduce the amount of code.

There are several terms to know about the Function template: instantiation and explicit concrete. The former is classified into implicit and explicit. The three are collectively called concrete. For a function template, for example:

Template <typename T>

T max (t a, t B) {If (A> B) return a; else return B ;}

If you call Max (4, 5) directly, it is an implicit instantiation, while max <double> (4, 5) is a display instantiation.

If you redefine the following function template <> max <int> (int A, int B) {return 10000 ;}, then max (4, 5) is explicitly embodied, this is because a new function definition for this call is given, not just the template instantiation.

 

Name Modification

So many functions with the same name are actually different in the compiler. The function name will change after compilation, and all information in the function parameter list will be added to the new function name, different compilers implement different rules.

 

Reload parsing:

Reload parsing involves the following steps:

Step 2: create a list of candidate functions. The template function contains the same name as the called function.

Step 2: Use the list of candidate functions to create a list of feasible functions. These are all functions with the correct number of parameters. Therefore, there is an implicit conversion sequence, including the exact match between the real parameter type and the corresponding parameter type. For example, a function call using the float parameter can convert the parameter to double to match the double parameter, and the template can generate an instance for the float parameter.

Step 2: Determine whether there are the best feasible functions. If yes, use it. Otherwise, the function call fails.

 

The most complex process is to determine whether there are the best feasible functions.

The function template C ++ 98 has the following rules: Non-template functions give priority to the general template because of the specific and general templates. Also: (priority from high to low)

1. Exact match, but regular functions are template-based.

2. Improve the conversion (for example, char and short are automatically converted to int, and float is automatically converted to double ).

3. standard conversion (for example, convert int to Char and long to double ).

4. User-Defined conversions, such as those defined in the class declaration.

Some of the exact matches are irrelevant conversions:

Type-> type &

Type &-> type

Type []-> type *

Type (argument-list)-> type (*) (argument-list)

Type-> const type

Type-> volate type

Type *-> const type *

Type *-> volate type *

It is called an insignificant conversion because if the real parameters on the left are substituted into the function, the parameters declared as the two parameters on the left and right have the same priority in the call. For example, type-> type & when we define FN (int x) and FN (Int & X), the compiler reports an error when FN (a) is called, because the conversion from type-> type & is irrelevant. They are all completely matched.

 

However, when both functions are completely matched, reload parsing can still be completed.

1. pointers and references pointing to non-const data take precedence over non-const pointers and reference parameter matching.

2. If a function is not a template function but another function, in this case, a non-template function is superior to a template function (including the actual embodiment ).

3. If both fully-matched functions are template functions, the template functions are preferred. For example:

Template <typename T> t fn (t a, t B) {...} exists ){...} and template <typename T> T * fN (T * a, T * B ){...} if two pointers are passed to call a function, the latter template is more specific and will be called.

 

 

 

 

Chapter 9 Memory Model and namespace

This chapter details the memory management mechanism of a program, how the code affects the memory, and how the programmer uses the language to achieve the expected memory allocation.

 

Project

A project will be composed of multiple units (files), each file can be compiled separately, and finally the IDE will link these files, the introduction of multiple files brings more trouble. Files can be organized as follows:

Header file: Contains structure declarations and prototypes of functions using these structures.

Source code file: contains the code of the function related to the structure.

Source code file: Contains code for calling functions related to the structure.

This seems to be very similar to calling a library function. We can compile the source program by including the header file (the header file contains the prototype of the function we used, then, call the function definition through the Linked Library function.

 

Header file

The header file should only contain the following content:

Function prototype.

Use a symbolic constant defined by # define or Const.

Structure declaration.

Class declaration.

Inline functions.

Header files won't be compiled, so there won't be *.. CPP files provide them with a prototype to call functions, so that the files are compiled and then linked to other programs. CPP file generation *. o file to find the definition of a function.

 

Terms for program and memory change

Storage continuity, scope, and connectivity

 

Storage continuity

Storage persistence includes automatic storage persistence, static storage persistence, dynamic storage persistence, and thread storage persistence (C ++ 11 ). It emphasizes the lifecycle of a memory (from being used to being released ).

 

Scope

That is, the range that a variable can use in a file. First, we will introduce the Declaration area: Declaration areas are divided into files and code blocks, which is easy to understand. Potential scope: it is a potential scope from the definition of the variable location to the declaration area. The scope is to exclude the potential scopes covered.

 

Linking

Linking is whether a variable can be used by reference declarations in other files through linking.

 

Single-definition rules

A single definition rule means that a variable can be declared only once, but can be referenced multiple times. The reference declaration is in the form of extern type typename, and other forms are considered as definition declarations, including the confusing form of extern type typename = value.

 

5 variable Storage Methods

 

C ++ 11 auto register

In C ++ 11, the meanings of the auto and register keywords have changed. The latter replaces the meaning of the former, and the former changes to automatic type inference.

 

CV-Qualifier and mutable

Const and volatile are CV-delimiters. The former does not need to be said. The latter tells the compiler that the variable may change without modifying the memory in the code, this prevents the compiler from optimizing the performance.

Mutable, used to modify member variables. Member variables modified with mutable can still be modified after the entire structure is const-qualified.

 

Function linking

The function is also linked, and the default is an external variable. The link is external, and the declared link of static display must be added to the internal function. This feature satisfies the need for a reference to declare a function in the header file, that is, the function prototype we often call.

 

New operator and Positioning new operator

The new operator uses the pointer to flexibly use the dynamic memory. The new operator must contain the <New> header file. It can specify a starting address and declare a piece of memory, which can be used to re-initialize the opened memory block.

 

Namespace

The appearance of the name makes the variable name more reassuring. The namespace can be global or in another namespace, but not in the code block. Variables defined in a non-code block by name have a namespace and the global variable is:. Therefore, variables with the same name defined in different namespaces can be located by the scope resolution operator. C # This language defines a namespace for each class. In addition, using declaration is safer than using to compile commands. Using declares that the field can be directly accessed by name. If a conflict exists, an error is returned, and the using compilation command will be overwritten in the event of a conflict. The Using Declaration will also import all the overloaded versions of a function.

 

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.