Const thinking

zhaozj2021-02-16  58

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 introduced 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, some places 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 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!

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

New Post(0)