Const thinking

xiaoxiao2021-03-05  24

Const thinking

Author: Unknown Source: Unknown Joined: 2004-8-10

Development documentation

1. What is a const? Frequent type means that the type of type modifier constant explains, the usual type variable or the value of the object cannot be updated. (Of course, we can steal the column for updates:) 2, why introduce const? The initial purpose of Const is exactly to replace the precompiled instructions, eliminating its shortcomings while inheriting its advantages. 3. What is the main role in cons? (1) You can define the constant constant and have invariable. For example: const Int max = 100; int Array [MAX]; (2) Easy to perform type checks, making the compiler more about processing content, eliminating some hidden dangers. For example: Void F (const I) {.......} The compiler will know that I is a constant, not allowed to modify; (3) can avoid the meaning of the fuzzy number, which can also be very convenient Adjustment and modification of parameters. Like the macro definition, you can do it without bad, change it! As in (1), if you want to modify the content of Max, you only need: const int max = you want; you can! (4) Protecting the modified things, prevent accidental modifications, enhance the robustness of the program. Or the above example, if you modify I, the compiler will report an error; for example: Void F (const I) {i = 10; // error!} (5) provides a reference for the function overload. Class A {... Void F (INT i) {...} file: // A function void f (INT i) const {...} file: // Previous The overload of the function ...}; (6) saves space to avoid unnecessary memory allocation. For example: #define pi 3.14159 file: // constant macro Const Doulbe Pi = 3.14159; file: // does not put PI in the ROM ... Double I = Pi; file: // PI allocates memory, no longer allocation in the future! Double I = Pi; File: // Macro replacement during compilation, allocate memory Double J = Pi; file: // No memory assignment double J = Pi; file: // Macro replacement, and allocate memory again! Constance Constant From the assembly point of view, just gives the corresponding memory address, not the only number as #define is the number, so constants defined in the process of only one copy during the operation, and # Define defined constants have several copies in memory.

(7) Improve efficiency. The compiler usually does not assign storage space for normal constant constants, but saves them in the symbol table, which makes it a constant during compilation, and there is no operation of the memory and read memory, making it efficient. 3, how to use const? (1) The general constant of the modified general constant refers to the simplicity of the constant. This constant is defined, and the modifier Const can be used before the type specifier can be used before the type specifier. For example: int const x = 2; or const INT x = 2; (2) modified constant group definition or description of a constant group can be used in the following format: int Const a [5] = {1, 2, 3, 4, 5} Const Int A [5] = {1, 2, 3, 4, 5}; (3) Modifying the normal object constant object refers to the target constant, the definition format is as follows: Class A; const a a; a const a; definition often When the object is, it is also initialized, and the object cannot be updated, and the modifier const can be placed behind the class name or in front of the class name. (4) Modified normally pointer const * a; file: // constitutive object, A variable, a point to the object whose object is not variable int const * a; file: // constly, the object, A variable, A point to the object is not variable int * const a; file: // const Demodifier A, A is not variable, a point to the object variable const * const a; file: // Pointer A and A point to the object (5) The modified common reference to use the const modifier can also explain the reference, the referenced reference is commonly referenced, and the object referenced by this reference cannot be updated. Its definition format is as follows: const Double & V; (6) Form of normal parameters of the modified function can also modify the delivery parameters of the function, the format is as follows: Void fun (const Int var); tell the compiler VAR in the function body in the function body Change, thereby preventing some unintentional or wrong modifications of the user.

(7) Return value of the modification function: const modifier can also modify the return value of the function, is the return value cannot be changed, the format is as follows: const Int fun1 (); const myclass fun2 (); (8) member functions of the modifier class : Const modifier can also modify the members of the class, the format is as follows: Class classname {public: int fun () const; .....}; This cannot modify the data in the class when calling the function FUN (9) Quote Const constant Extern const I; file: // correct reference EXTERN Const Int J = 10; file: // Error! Constants cannot be assigned again, but also note that constants must initialize! For example: Const Int i = 5; 4, a few points worth discussing: (1) What does Const mean? Said so much, what do you think Const means? A modifier? Interface abstraction? A new type? Perhaps, when Stroustup initially introduces this keyword, it is only possible for the object to put ROM. For Const objects, C is allowed to initialize them, and he is allowed to dynamically initialize him. The ideal const object should be writable before its constructor is completed, and it is also writable after the encersion function is executed. In other words, the Const object has the result of completing the complement of the constructor to the exception. Vigify, if this rule is violated, the result is undefined! Although we put const in the ROM, this is not able to ensure any form of constant, and we will give specific methods later. Regardless of the Const object being placed in the ROM, it can only be guaranteed by the storage protection mechanism, and this object has not changed for the user. In other words, the waste collector (we will discuss in detail later, this will have no problem with the revision of a constant) or the database system. (2) Bit Const v.s. Abstract const? There are several ways to explain the keyword Const. The most common is that bit elevation const and abstract const. Let's take an example: Class a {public: ... a f (const A & a); ...}; if the abstract const is explained, that is, the F function will not change the reference The abstract value of the object, if the bit element const is interpreted, then the F function does not change any bit of the referenced object. We can see that the bit interpretation is the definition of C to the Const problem, and the Const member function is not allowed to modify any of the data of the object.

Why is this? Because the use of bit yuan const has 2 benefits: the biggest advantage is to easily detect events specified by the bit constant: The compiler is only looking for if there is no assignment for the data member. Also, if we use a bit constant, then for some relatively simple Const objects, we can put it safely into the ROM, which is undoubtedly a very important way for some programs. (About optimization, we specialize in discussing) Of course, the CONST is also shortcoming, or if the abstract const has not generated. First, the abstraction of the bit constant is lower than the level of abstract consts! In fact, everyone knows that the lower the abstraction level of a library interface, the more difficult it is to use this library. Second, use the library interface of the bit constant will expose some of the implementation details of the library, and this often brings some negative effects. Therefore, in the details of the library interface and the program, we should use abstract const. Sometimes, we may want to make some other explanations for Const, then pay attention, currently, most of the interpretation of Const is unsafe, here we don't have examples, you can think about it yourself. In short, we try to avoid reinterpretation of Const. (3) What are the constraints on constants within the class? See the following example: Class A {Private: const Int c3 = 7; // ??? static int C4 = 7; // ??? static const float c5 = 7; // ??? ..... .}; Do you think 3 sentences above? Oh, it is wrong! When using this type of initialization syntax, constant must be an integer or enumeration type initialized by a constant expression, and must be static and const form. This is obviously a very serious limit! So why do our standard committees do this? In general, classes are declared in a header file, while header files are included in many units that are called. However, in order to avoid complex compiler rules, C requires only one separate definition of each object. This rule is destroyed if C is allowed to define an entity that occupy a memory as an object within a class.

(4) How to initialize the constant within the class? One way is static and const and use, internally, as example above; another very common method is to initialize list: Class A {public: a (int i = 0): Test (i) {} private: const INT i;}; there is another way to initialize external, for example: Class A {public: a ()} private: static const Int i; file: // Note must be static! }; Const Int A :: I = 3; (5) What are the specifics of the constant and array? We give the following code: const Int size [3] = {10, 20, 50}; int Array [size [2]]; Is there any problem? By the way, the compilation is not available! why? Const can be used for collection, but the compiler cannot store a collection in its symbol table, so you must allocate memory. In this case, Const means "a piece of storage that cannot be changed". However, its value cannot be used when compiling, as the compiler does not need to know the stored content when compiling. Natural, as the size of the array is not :) You look at the example below: Class a {public: a (int i = 0): TEST [2] ({1, 2}) {} file: // you Do you think? PRIVATE: Const Int Test [2];}; VC6 compiled, why? About this problem, ago, NJBOY asked me what happened? I asked him: "What do you think?" He thought about it, giving a explanation, everyone can see: We know that the operation of the compiler stack initialization list is within the constructor, explicitly call the available code before initialization The order is based on the order of the data declaration. There should be no problem in initialization timing, then only the compiler has done a group of hands! In fact, what do you do, I don't know, I have to guess him: The compiler search TEST is found to be a non-static array, so I allocate memory space, here you need to pay attention, it should be allocated, Not allocating TEST [0], then initialize the initialization list, then allocate TEST [1], which causes the initialization of the array to actually assign a value! However, constants are not allowed to assign values, so they cannot pass.

Oh, I saw this paragraph, I really made me laugh! NJBOY Don't blame you :) I explained this: C standard has a provision, not allowed to be internally initialized in the class, so the initialization is incorrect! For him, you can only initialize the outside of the class. If you want it to pass, you only need to declare static, then initialize. Here we see that there is no special combination of constants and arrays! Everything is the disaster of the number! (6) Is the THIS pointer not a const type? The THIS pointer is a very important concept, how do you understand her? Maybe this topic is too big, then we narrowed some: What type of this pointer is the THIS? This is to see the specific situation: If this pointer is just a class type in a non-Const member function; if the this pointer is a const class type; if the this pointer is a volatile, this pointer is a volatile Class type. (7) Is Const until an overloaded reference object? Let's take a look at the following example: Class A {... Void F (INT i) {......} file: // A function void f (int i) const {... } File: // The overload of the last function ...}; the above is no problem, then below? Class A {... Void F (INT i) {...} file: // A function void f (const INT i) {...} file: //? ? ? ? ? ...}; this is wrong, compiled. So, is it to explain the const of the internal parameters does not overload? Look at the example below: Class A {... Void F (int & {......} file: // A function void f (const INT &) {...} file: //? ? ? ? ? ...}; this program is correct, it seems that the conclusion above is wrong. Why is this so? This should involve the transparency problem of the interface. When the value is passed, this is transparent. This is transparent. The user does not know what the function is refined. In this case, it is meaningless, so the specified cannot be overloaded! When the pointer or reference is introduced, the user will have a certain understanding of the operation of the function, no longer transparent, and the overload is meaningful, so it may be overloaded.

(8) What is the allocation of memory for const? The following is the possible situation I think, of course, some compilers have been optimized and may not allocate memory. A. When a non-static class member; b, when used for a collection; C, when the address is taken; D, when the value is obtained by a function inside the main function body; E, CONST Class or Struct There is a user-defined constructor. Function, destructor or base class; F, when the length is longer than the length of the computer; g, the const; h in the parameter, the extern is used. I don't know if there is any other situation, welcome the expert pointing :) (9) Temporary variable is constant? In many cases, the compiler must establish a temporary object. Like any other object, they need to store spaces and must be constructed and deleted. The difference is that we have never seen the compiler to determine their stay and the details they exist. For the draft C standard: The temporary object is automatically integrated. Because we usually have access to temporary objects, you cannot use information related to it, so tell the temporary object to make some changes may be wrong. Of course, this is related to the compiler, for example: VC6, VC7 extends this, so use the temporary object to do the left value, the compiler does not report an error.

(10) Will there be a problem with Static? Suppose there is a class: Class a {public: ... static void f () const {...} ...}; we found that the compiler will report an error because in this situation STATIC is not able to coexist with const! why? Because Static does not have this pointer, but constly modifies the THIS pointer, so ... (11) How to modify the constant? Sometimes we have to modify the data within the class, but our interface is declared constant, what should I deal with? My opinion on this question is as follows: 1) Standard usage: mutable class a {public: a (int i = 0): test (i) {} void setValue (int i) const {test = i;} private: mutable int = i;} private: Mutable Int Test; file: // Here you handle! }; 2) Forced conversion: const_cast class a {public: a (int i = 0): TEST (i) {} void setValue (INT i) const {const_cast = i;} // ! Private: int test;}; 3) flexible pointer: int * Class a {public: a (int i = 0): Test (i) {} void setValue (int i) const {* test = i;} private: INT * TEST; file: // Treated here! }; 4) Undefined processing class a {public: a (int i = 0): TEST (i) {} void setValue (int *) const {INT * P = (int *) & test; * p = i; } // Treated here!

Private: int test;}; Note, although this can be modified, the result is undefined, avoiding use! 5) Internal handling: this pointer class a {public: a (int i = 0): TEST (i) {} void setValue (INT i) const {((a *) this) -> test = i;} // Here you are working here! Private: int test;}; 6) Most alternative: Space layout Class a {public: a (int i = 0): TEST (i), c ('a') {} private: char C; const Int Test }; Int main () {a a (3); a * pa = & a; char * p = (char *) Pa; int * pi = (int *) (p 4); // Using edge adjustment * Pi = 5; file: // Change the value of TEST here! Return 0;} Although I gave 6 methods, I just want to explain how to change, but I have the first use, and the other five kinds of use, we don't advocate, don't be written because I wrote it, you will This is, otherwise, I am really wrong :) (12) Finally, let's discuss the dynamic creation of a constant object. Since the compiler can initialize constants, you can naturally create, for example: const INT * pi = new const Int (10); here you should pay attention 2 points: 1) The const object must be initialized! Therefore, (10) is not possible. 2) The pointer returned by New must be a const type. So can we create a number of arrays? The answer is negative because the NEW built-in type array cannot be initialized. Here we ignore the array is type type, and we also make such an ignore for the internal array of interiors, because this involves the array of questions, we will discuss later.

(Const Discussion Second) Correct use of Water Drop Stones Co-use CONST Chu Yunfeng 2004-9-16 14:46:00 / Basic explanation const is a keyword of a C language, which defines a variable that is not allowed to be changed. Using const can improve the robustness of the program to a certain extent, in addition, when watching others code, clear understanding of the role of Const, there are some helps to understand the other party. Although this sounds very simple, in fact, the use of Const is also a subtle place in the C language, where is it? Please see the following questions. Question: Const Variable & Constant Why is the example of the following example to initialize the array, ANSI C's compiler reports an error?

Const int N = 5; Int a [n]; answer and analysis: 1), this problem discusses the difference between "constant" and "read-only variable". Constants are definitely read-only, such as 5, "ABC", etc., must be read-only because there is no place to store its value at all, and of course it is not able to modify it. The "read-only variable" is a place to store it in memory, but this value is defined by the compiler that is not allowed to be modified. C Language Keyword Const is used to qualify a variable that is not allowed to be changed. Qualifier. The variable N is modified as a read-only variable in the above code, but it is not a constant. The dimension must be "constant" when the array definitions specify the array definitions, and "read-only variable" is not possible. 2), Note: In ANSI C, this way of writing is wrong because the size of the array should be a constant, and const Int n, n is just a variable (constant! = Non-variable variable, but in standard C , this Defining a constant, this way is pair), in fact, according to the compilation process and memory allocation, this usage should be reasonable, just the provisions of the ANSI C pairs to array. 3), then what is the constant in the ANSI C language? The answer is an enum type and #define macro, both of which can be used to define constants. Question: Const Variables & Const Limited Content The following code compiler will report an error. Which statement is wrong?

Typedef char * pstr; char string [4] = "abc"; const char * p1 = string; const pstr p2 = string; p1 ; p2 ; answer and analysis: The problem is in P2 . 1), the basic form of Const use: const char m; defining m is not variable. 2), replace the m, const char * pm in the 1 style; define * PM is not variable, of course, the PM is variable, so P1 is pair in the problem. 3), replace 1 type char, const newtype m; define M unality, the charptr in the problem is a new type, so P2 is not variable, P2 is wrong. Question: Const variable & string is constantly questionable? Is there any problem with the code below?

Char * p = "I'm Hungry!"; P [0] = 'I'; answer and analysis: The above code may cause illegal write operations of memory. The analysis is as follows, "I'm Hungry" is essentially a string, and constant is often placed in a read-only memory area and cannot be written. p Initially point to this read-only memory, and P [0] = 'i' attempts to write this place, the compiler will certainly not agree. Question: Const variable & string constance 2 CHAR A [3] = "ABC" legal? What hidden dangers do it use? Answer and analysis: This is legal in standard C, but its living environment is very narrow; it defines an array of size 3, which is initialized to "ABC", note that it does not usually string terminator '/ 0 ', So this array just looks like a string in the C language, which is essentially, so all functions for processing the string, such as strcpy, printf, etc., can not be used on this false string. Question 5: Const & Pointer Type Declaration CONST is used to modify a constant, there are two ways to write, then, what is the content that is unambiguous with const below? 1), const in front const Int nvalue; // Nvalue is constconst char * pContent; // * PContent is const, PContent variable const (char *) PContent; // pContent is const, * PContent variable char * const pContent; // pContent is const, * pContent variable const Char * const pContent; // pContent and * PContent are const 2), const is behind, with the above declaration

INT const nvalue; // nvalue is constchar const * pContent; // * PContent is const, pContent variable (char *) const pContent; // pContent is const, * PContent variable char * const pContent; // pContent is constant , * PContent; // PContent and * PContent are all Const Answers and Analysis: CONST and pointers are used in a C language a very common confusion, in actual development, especially When someone else's code, often because it is not good to judge the author's intention, let's talk about my judgment principle: along the * number one line, const and who are on the side, then who is const, the constant element is it. You can look at the actual significance of the above declaration according to this rule, and I believe that the order will be at a glance. In addition, it is necessary to note: For const (char *); because char * is a whole, it is equivalent to a type (such as char), so this is constative pointer to const.

转载请注明原文地址:https://www.9cbs.com/read-35618.html

New Post(0)