Lecture 9: protection of shared data and dynamic processing of Objects

Source: Internet
Author: User

Lecture 9: protection of shared data and dynamic processing of Objects

Basic Requirements

* Grasp: definitions of common objects, methods for introducing data members of common objects, and common references of objects.
* Understanding: Definitions and references of common object pointers.
* Understand: the dynamic creation and release of objects.
Key points and difficulties
* Definitions of common objects; methods for introducing data members of common objects; and common references of objects.

I. Protection of shared data

Although a lot of effective measures (such as private protection) have been taken to increase data security, some data is often shared, such as real participation parameters, variables and references, data and pointers allow people to access the same data object in different ways on different occasions. Some unintentional misoperations may change the data, which is not expected to happen.
To enable data to be shared within a certain range, and ensure that the data is not modified at will, you can use const to define the relevant data as constants.

1. Common objects

The general form of defining a common object is:
Class Name const object name [(real parameter table)]
;

Const class name object name [(real parameter table)];
They are equivalent.

Note:
1. When defining an object, specify the object as a regular object. The data member in a constant object is a constant variable and must have an initial value. In this way, the values of all data members in the TL object cannot be modified in all the fields. Objects that wish to ensure that data members are not changed can be declared as common objects.
2. If an object is declared as a regular object, the non-const member functions of the object cannot be called (except the implicit constructor and destructor automatically called by the system ).
3. To prevent the function from modifying the values of data members in a common object. In a function, the values of data members in a common object are not allowed to be called, because the programmer's attention cannot be used only to ensure that the program does not encounter errors. The compilation system fully considers possible situations, block insecure factors.
4. The compilation system cannot enter the function to check its code to see if it has modified the value of data members in a regular object. In fact, the function definition and function declaration may not be in the same source program file. Compilation is based on a source program file. It cannot be used to determine whether there is a conflict between the two source program files. If there is a mistake, it can only be found in the connection or running stage. This makes debugging procedures inconvenient.
5. Now, the compilation system only checks the function declaration. if it finds that the member function of a common object is called and the function is not declared as const, an error is returned.
6. Sometimes there are requirements for programming. You must modify the value of a data member in a regular object (for example, the value of a variable count in the class should be changeable ), in consideration of the actual programming needs, ANSI performs special processing and declares mutable as the data member. For example:Mutable in count;Declare count as a variable data member, so that you can use the member function declared as const to modify its value.

2. Regular object member (class)

You can declare a member as a const when declaring a class, that is, declaring a common data member and a function as a common member.

① Regular data member
The function and usage are similar to common variables. The key word const is used to declare a common data member. The values of common data members cannot be changed. Note: You can only initialize common data members through the parameter initialization table of the constructor.

For example, hour, a common data member, is declared in the class body:
Const int hour; // Declare hour as a regular data member

Note:
The method of assigning an initial value to a regular data member in the constructor cannot be used. The following usage is invalid:
Time: Time (int h)
{Hour = H ;}// Invalid because a common data member cannot be assigned a value.
If a constructor is defined outside the class, it should be written in the following form:
Time: Time (INT h): hour (h ){}// Call the parameter initialization table to initialize hour, a common data member. After the class body declares that a data member is a common data member, the value of this data member in all objects of this class cannot be changed, but the value of this data member in different objects can be different (given when defining the object ).

② Common member functions

Definition of common member functions: type function name const

Note:
1. If you declare a member function as a common member function, you can only reference the data members in this class, but cannot modify them. For example, you can only use them to output data. Common member functions can reference non-const data members in this class or modify them.
2. the const keyword is required when declaring and defining a function. You do not need to add the const keyword when calling the function. A common member function can reference a const data member or a non-const data member.
3. a const data member can be referenced by a const member function or a non-const member function. The specific situation can be represented in table 1 below.

How can we use regular member functions?
(1) If the values of some data members in a class can be changed while those of other data members cannot be changed, you can declare some data members as Const, to ensure that the value is not changed. Non-const member functions can reference the values of these data members and modify the values of non-const data members.
(2) If you require that the values of all data members cannot be changed, you can declare all data members as const, or declare the object as const (regular object ), then, the coast member function is used to reference the data member, which plays a "double insurance" role and effectively ensures that the data member is not modified.
(3) If you have defined a regular object, you can only call the const member function, but not the non-const member function (whether or not these functions modify the data in the object ). This is to ensure data security. To access data members in an object, you can declare all member functions in a common object as a const member function, and ensure that the data members in the object are not modified in the function.
Do not mistakenly think that the member functions in a common object are always member functions. A common object only ensures that the values of all data members are not modified. If the const declaration is not added to the member function of a common object, the compilation system treats it as a non-const member function.
Another point should be noted: A common member function cannot call another non-const member function.

3. A constant pointer to an object

Definition: declare the pointer variable pointing to the object as the const type and initialize it. In this way, the pointer value remains unchanged and cannot be changed at the beginning, that is, its orientation remains unchanged.

The common pointer to an object is defined as follows:Class name * const pointer variable name = object address;

Note:
1. Time Tl (10, 12, 15), T2;// Define the object
Time * const ptrl = T1// The const is located before the pointer variable name, which specifies that the ptrl value is a constant value and points to the object T1, and cannot be changed afterwards;
Ptrl = & T2; // Error. ptrl cannot be changed
2. You can also initialize the pointer variable.
3. The value of a constant pointer variable pointing to an object cannot be changed, that is, it always points to the same object, but it can change the value of a data member pointing to an object (such as T1.
4. A regular pointer is often used as a function parameter to prevent changing the value of the pointer variable during function execution so that it always points to the original object. If the value of this parameter is modified during function execution, the compilation system will find an error and provide an error message, which is more reliable than manual modification.

4. pointer variables pointing to common objects

To make it easier for readers to understand the concept and use of pointer variables pointing to a common object, first understand the pointer variables pointing to a constant variable, and then further study the pointer variables pointing to a common object.

The general form of a pointer variable that defines a pointer to a constant variable is:

Const type name * pointer variable name;

Example:The following defines a pointer variable PTR pointing to a constant variable:
Const char * PTR;
Note: The position of const is at the leftmost. It is closely connected to the char type name, indicating that the char variable pointed to by the pointer variable PTR is a constant variable and cannot be changed through PTR.

Note:
(1) If a variable has been declared as a constant variable, it can only be pointed to by a pointer variable pointing to a constant variable, rather than a general variable (pointing to a non-const type variable) the pointer variable points to it.
(2) A pointer to a constant variable can point to a variable declared as a const in addition to a constant variable. In this case, you cannot use this pointer variable to change the value of this variable.
(3) If the form parameter of a function is a pointer to a non-const variable, the real parameter can only be a pointer to a non-const variable, rather than a pointer to a const variable, during function execution, you can change the value of the variable (that is, the variable pointed to by the real parameter pointer) pointed to by the form parameter pointer variable. If the form parameter of a function is a pointer to a const-type variable, it is obvious that the value of the variable pointed to by the pointer variable cannot be changed during function execution. Therefore, the real parameter is allowed to be a pointer to the const variable, or a pointer to a non-const variable. See table 2.


Table 2 ing between the form parameter and the real parameter using pointer Variables

The above correspondence is consistent with the pointer variable described in (2) and the variable to which it points: pointer variables pointing to constant variables can point to const and non-const variables, while pointer variables pointing to non-const variables can only point to non-const variables.

The above is a pointer variable pointing to a constant variable. The concept and usage of a pointer variable pointing to a constant object are similar to this. You only need to replace "variable" with "object.
(1) If an object has been declared as a constant object, it can only be pointed to by a pointer variable pointing to a constant object, rather than a general object (pointing to a non-const object) the pointer variable points to it.
(2) If you define a pointer variable pointing to a common object and point it to a non-const object, the object to which it points cannot be changed through a pointer.
(3) pointers to common objects are most commonly used in function parameters, so that they are not modified during function execution.
(4) If a pointer variable pointing to a common object is defined, it cannot be used to change the value of the pointed object, but the value of the pointer variable itself can be changed.

5. constant reference of object images

It was introduced in the past that a reference to a variable is the alias of the variable. Essentially, both the variable name and reference name point to the same memory unit. If the parameter is the reference name of the variable and the real parameter is the variable name, instead of opening up a bucket (often called a copy of a real parameter) for the form parameter, the address of the real parameter variable is passed to the form parameter (reference name), so that the reference name also points to the real parameter variable.

Example 8: a common reference of an object.
# Include <iostream>
Using namespace STD;
Class time
{ Public:
Time (INT, Int, INT );
Int hour;
Int minute;
Int sec ;};
Time: Time (int h, int M, int S)// Define the constructor
{ Hour = h;
Minute = m;
SEC = s ;}
Void fun (Time & T)// The parameter T is a reference to a time object.
{ T. Hour = 18 ;}

Int main ()
 { Time T1 (10, 13, 56 );// TL is a time object
Fun (T1 );// The real parameter is a time object. You can reference it to modify the value of the real parameter D.
Cout <t1.hour <Endl;// The output value of t1.hour is 18.
Return 0 ;}

If you do not want to modify the value of the real parameter T1 in the function, you can declare reference T as const (often referenced). The function prototype is
Void fun (const time & T );
The value of t cannot be changed in the function, that is, the value of the corresponding real parameter and T1 cannot be changed.
In object-oriented programming, common pointers and references are often used as function parameters. This ensures data security, prevents data from being modified at will, and does not have to create a copy of real parameters when calling a function. When Learning Section 8, you will know that each time you call a function to create a copy of a real parameter, you must call the copy constructor, which requires time overhead. Using Regular pointers and regular references as function parameters can improve program running efficiency.

6. Const Data Summary

This section describes const-type data and references, which can be used to protect shared data. Because there are many types of const data related to objects, and their forms are similar and confusing, This section summarizes them. For ease of understanding, it is expressed in a specific form. The object name is set to time. Using table 3, you can view the usage and differences of several types of const data at a glance, which is easy to view when necessary. The last row in the table is an object reference and does not belong to the const type data.

It may be difficult to understand the content introduced in the Fengjie, but it is hard to remember. Do not worry or remember it. In the future, you will gradually become familiar with and use them skillfully.

Ii. Dynamic Object creation and release

The object defined in the preceding method is static. during the running of the program, the space occupied by the object cannot be released at any time. For example, an object is defined in a function and is released only when the function ends. But sometimes people want to create an object only when they need to use it. They do not need to use this object to cancel it and release the memory space it occupies for other data. This improves the memory usage.
The C language uses the new operator to dynamically allocate memory, and the delete operator to release the memory space. This applies to objects. You can use the new operator to dynamically create objects and use the delete operator to cancel objects.

General format for dynamically allocating memory by the new operator:Object Pointer variable = new object name

The general format of the delete operator to release these memory spaces: Pointer variable of the delete object

Example:If you have defined a box class, you can use the following method to dynamically create an object:

Box * PT // Define a pointer variable P1 pointing to a box object
PT = new box;// The initial address of the new object is stored in PT.
Or: new box;// The object has no object name and the user does not know its address. This kind of object is called an unknown object. It does exist, but it has no name.

Note:
1. The editing system opens up a memory space and stores a box class object in the memory space to the PT pointer. In the program, you can access the new object through PT. For example
Cout <Pt-> height; // output the height of the object
Cout <Pt-> volume (); // call the volume function of the object to calculate and output the volume.
You can also initialize the newly created object when executing new. For example:
Box * PT = new box (12, 15, 18 );
2. Call an object either through the object name or pointer. A dynamic object created with new generally uses a pointer instead of an object name. It is mainly used in a dynamic data structure, such as a linked list. To access the nodes in the linked list, you do not need to use the object name, but store the address of the next node in the previous node, so that the previous node finds the next node and forms the link relationship.
3. When executing the new operation, if the memory volume is insufficient, the required memory space cannot be opened up. Currently, most compilation systems use new to return one. Pointer value. If the returned value is 0, you can determine whether the allocated memory is successful. According to the an61 standard, when a new fault occurs during execution, an "exception" is thrown. You can handle the exception based on the exception (for details about exception handling, see Chapter 8th ). However, the C 4-+ standard still allows the return in the case of a new fault. Pointer value. Currently, different compilation systems have different ways to handle new faults.
4. When you no longer need to use objects created by new, you can use the delete operator to release them. For example
Delete pt; // release the memory space pointed to by PT
This removes the object pointed to by PT. After that, the program cannot use this object. If you use a pointer variable pt to point to different dynamic objects successively, you should pay attention to the current pointer variable to avoid deleting the wrong object.
5. When executing the delete operator, the Destructor is automatically called before the memory space is released to complete subsequent cleanup.

Transferred from: http: // 210.44.195.12/cgyy/text/html/text/09.htm

 

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.