"Effective C + +" NOTE: I

Source: Internet
Author: User

Terms 2:prefer Consts,enums,and inlines to #defines

Try to replace # define with Const,enums,inline.

#define是预处理器中宏定义.

For example, # define PI = 3.1415926, this is equivalent to replacing all symbol occurrences in the code with the value 3.1415926 before compiling.

This blind substitution is mentioned in the book, and if, for some reason, an error message is given when the constant is applied, the error message mentions 3.1415926 instead of Pi, and we spend a lot of time tracking it when we have no idea about the value of 3.1415926 and where it comes from.

The reason is that the compiler does not put the PI symbol into the symbol table.

The workaround is simple, replace the macro with a constant: const double PI = 3.1415926.

The book also mentions a enumb hack used for array declarations (the compiler requires that the size of the array be known during compilation), and enum can replace a scenario in which a # define declares an array capacity.

Enum hack is the basic technique for template metaprogramming, which is described in detail in clause 48 (although I know little about template metaprogramming)

In fact, the trouble with # define is not just these. The most common is that a macro defines a function, such as # define MAX (int a,int b) a>b?a:b;

As mentioned earlier, the #define就相当于编辑器里的ctrl +h substitution function, if this is similar to the two larger function of Max is applied to such an expression: if (50+max (10,50) >= 100), The results you want may be 10 and 50, plus 50 and 100 compared to the size, that is, 50+50 >= 100 is true, but the compiler will actually explain this way >50? 10:50, the final 50+max (10,50) will return >= 100 to False.

Macro definitions often take precedence over operators when replacing them, and whenever you write a macro like Max and want it to work correctly, take a parenthesis for all of the actual. And because the macro definition is processed before compiling, it is not involved in the grammar check of the translation process.

But in fact we can avoid this kind of macro use completely. The book mentions the use of the template inline function, which also has the efficiency of the macro and all the predictable behavior and type safety of the general function.

For constants, replace # define with const, enum.

For macros similar to functions, replace # define with the inline function

Terms 3:use Const whenever possible

Use const whenever possible

Const is a versatile keyword for C + +. It allows us to specify a semantic constraint (that is, to specify an object that "should not be altered" in any case).

We can add a const modifier to variables, functions, member variables, pointers, and so on, so that they are marked as non-modifiable.

It is worth mentioning that the pointer is declared as const, either by declaring the pointer as a constant, or by declaring the pointer object (the pointer content)

In the book, I feel very good: If the keyword const appears to the left of the asterisk, indicating that the object is a constant, if it appears to the right of the asterisk, indicating that the pointer itself is a constant, if it appears on both sides of the asterisk, indicating that both the finger and the pointer are constants.

In addition, bitwise constness and logical constness were mentioned. It is mentioned that the compiler considers that the bitwise const can actually be modified, and the example in the book is a pointer to the address returned by the const member function. The pointer contents are then modified.

The logical Constness,const member function can then modify certain variables within the object it is working with. The book mentions bitwise constness constraints that release Non-static member variables with the mutable (mutable) keyword. I have encountered this situation because of the need to modify the status of the check in the const function, but I did it with a forced transformation, and I didn't know if I was doing the right thing.

Finally, the const and NON-CONST member functions avoid duplication, and when the contents of the const and NON-CONST member functions are basically consistent, in order to avoid code duplication, it should be implemented only once and reused, even if one of them calls another.

Then a constant de-casting (away constness), and the transition is not a good approach (clause 27), the correct way is to make the Non-const method call the const method to avoid code duplication, the process requires a transformation action

Well, I would like to use the code in the book, or write an example of it yourself.

#include <iostream>classA { Public:     enum{arysize =Ten}; A (): M_text ("123456789")     {     }    ~A () {}Const Char&operator[] (std::size_t POS)Const{printf ("Const function\n"); returnM_text[pos]; }    Char&operator[] (std::size_t POS) {printf ("Non-const function\n"); returnconst_cast<Char&> (static_cast<ConstA&> (* This) [POS]); }Private: std::stringM_text;};intMain () {a A; ConstA B =A; b[0];//Output const functiona[0];//output non-const function\n const function    return 0; }

This is an implementation, repeated calls, to avoid duplication of code. It looks like it's just a code, but in fact, if you do a lot of processing before you go back, what is the boundary check, the status check, the implementation will achieve our goal: code reuse.

A const can be applied to objects, function arguments, function return types, and member function bodies within any scope. Declaring a const can help the compiler detect errors and reduce the cost of debugging time-to-error.

When the const and NON-CONST member functions have a substantial equivalent implementation, making the Non-const version biased with the const version avoids code duplication and vice versa.

"Effective C + +" NOTE: I

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.