"Effective C + +" study notes-clause 02

Source: Internet
Author: User



************** **************   First, accustoming yourself to C + + **************************** 


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


The previous clause, let me correctly understand C + +, is not an integrated language, but a federation,

And this one clause is correcting some of our behavioral habits.


Use const, enum, inline rather than #define as much as possible

This is going to be about the compiler and the preprocessor ,

The content set by the #define is removed at the time of the preprocessor, so the compiler will not see it.

At this point, this problem can occur:

#define Aspect_ratio 1.653

And when aspect_ratio problem, will not error this constant, but error 1.653 this number,

--why?

The name you are using may not be entered in the symbol table.

In the compiler, these variable constant names are summed in the symbol table.

However, this constant is removed by the preprocessor and therefore does not enter the symbol table, so if a compilation error occurs, the error message mentions 1.653 instead of Aspect_ratio

This is a lot of unnecessary waste of time for us to track down and find fault.

If you use const instead:

Const double aspectratio = 1.653; Because the non-# define name should also have a corresponding specification change

At this point, the constant name will enter the symbol table, so if the compilation error, the error message back to Aspectratio


More than that, for floating-point constants, the use of const constants may result in a smaller number of codes than # define , because the preprocessor "blindly" replaces the macro name Aspect_ratio with 1.653 may result in multiple copies of object code (target code) 1.653, if the use of Const will eliminate the same situation.


Also, there are two special cases for const replacement #define:

① definition constant Pointers (constant pointer)

defining a constant pointer in a header file requires two const, and my understanding is that a defined pointer cannot point to another address, and one that defines the contents of the pointer as immutable.   This will be specifically discussed in the next article.

One more thing is that for defining a string,

With the const std::string authorname ("Scott Meyers");

Superior to const char* Const AUTHORNAME = "Scott Meyers";


②-specific constants about class

This is a concept about scope (domain), if you want to limit a constant scope to a class , you must make this constant a member (member) within the class, in order for the constant in this class to have at most one entity, It must also be made into a static (static) member.

Of course, this cannot be done with # define, because # define does not pay attention to the scope, once it is defined, it works in the subsequent compilation process, unless it is somewhere #undef, so the const is encapsulated.

Also, a const within a class is a declarative rather than a definition, and if the compiler does not require you to present a definition to it, you can do so:

Class Gameplayer{

Private

static const int numturns = 5;

int Scores[numturns];

......

};


const int Gameplayer::numturns; //constants have been obtained at the time of declaration, it is not necessary to set the initial value

This is the "in-class" initial setting,

This setting also has a limit, which requires constant static in class and integral type (integer type) {For example: Ints,chars,bools}

But here the limit is for integer type, if it is other type, you can declare the initial value within the class, and then set the initial value directly outside the class definition .




OK, with respect to const, the next step is enum.


for this scenario, if the class requires a class constant value during compilation, the It happens that the compiler does not support or allow the static integer class constant to complete the In-class initial setting, and the enum hack compensation method can be used .

Its theoretical basis is-- a numeric value that belongs to the enumerated type (enum type) can be used as a right-filled int

Cases:

Class Gameplayer{private:    enum {numturns = 5};    int scores[numturns];    ......};

Of course, Enum does more than that, and there are many reasons why we must know it.

① enum hack behaves like a #define rather than a const , taking a const address is legal, and taking an enum and a # define address is often illegal, and enums, like #define, will never cause unnecessary memory waste.

②enum hack is the basic technology of template metaprogramming (templated meta-programming)




Then is the inline aspect


One common # define misuse scenario is to use it to implement macros (macro).

Macros look like functions, but do not incur additional overhead from function calls.

In the following example, the macro is holding the macro argument, calling the function f:

Call F#define Call_with_max (b) f ((a) > (b) with a large value of a and B (a): (b))

To tell the truth, the macro-length is really going to make people miserable ...

This is just simple to take the larger call F, if the complex point of the function, that screen dare not think!

PS: Note that whenever you write a macro with an argument, you need to enclose all the arguments in the macro with parentheses.

Example of calling it:

int a = 5, b = 0; Call_with_max (++a,b);    A is accumulated two times Call_with_max (++a,b+10);    A is accumulated once

Here, before F is called, the sum of a is determined by "what is it compared to"?


At this point, you need a template inline function to solve the problem:

Template<typename t>inline void Callwithmax (const t& A, const t& b) {    F (a > B? a:b);}

In addition, since this is a real function, it adheres to the concept of scope (scope) and access rules , so it can be encapsulated within a class , of course, this is a macro cannot do.


Conclusion:

Despite the const, enum, and inline, we have reduced the need for preprocessor, especially #define, but not completely eliminated. #include is still a necessity, #ifdef/#ifndef也继续扮演控制编译的重要角色. There is no time to retire to the preprocessor, but we can definitely give it a longer vacation.



Please remember:

① for simple constants, it is best to replace them with const objects or enums #define

② for macros that resemble functions, it is best to replace the #define with the inline function instead



End ....

"Effective C + +" study notes-clause 02

Related Article

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.