"Effective C + +" study notes-clause 03

Source: Internet
Author: User
Tags bitwise

*************************************** Reprint Please specify the Source: Http://blog.csdn.net/lttree ********************************************


First, accustoming yourself to C + +


Rule 03:use const whenever possible.

Article 03: Use the const as much as possible


A const is a constant that allows you to specify a semantic constraint that the compiler enforces.

Versatile Keyword const has a variety of uses:

① the constants in the global or namespace scope outside the classes

② an object declared static in a file, function, or chunk scope (block scope)

③ uses it to modify static and Non-static member variables inside classes


A few important functions

1. For pointers

For pointers, you can set the pointer itself, the pointer's point, or both (or neither) const

The resolution method is also simple: if the const appears to the left of the asterisk (*), indicating that the object referred to by the pointer is a constant, and if it appears on the right, the pointer itself is a constant.

From this, it can also be extended to iterators (iterator)

If you want to indicate that the iterator must not point to something different, but what it refers to is something that can be changed:

Const Std::vector<int>::iterator ITER
Conversely, iterators can point to different things, but the meaning of the content cannot be changed:

Std::vector<int>::const_iterator ITER

2. The most powerful usage--for the application of function declarations

In a function declaration, a const can be associated with a function return value, each parameter, and the function itself.

The return value of the ① function

The function returns a constant value, often reducing the surprises caused by customer errors without compromising security and efficiency.

Parameters of the ② function

Declare them as const unless you need to change the parameters or local const objects. Just a few characters can help you save a lot of trouble.

③ function itself (const member function)

There are two reasons for a const implementation on member functions:

<1> They make the classes interface easier to understand (you can clearly know which function can change the object's content and which cannot)

<2> they make it possible to "manipulate a const object". This is the basis for the "pass by reference-to-Const transfer Object" technique.

Also, there is an important feature in overloading.

For a class, two functions:

Class Textblock{public: ...    .    Const char& operator[] (std::size_t position)  Const    {  return text[position];  }     char& operator[] (std::size_t position)    {  return text[position];  } Private:    std::string text;};

As long as you overload operator[] and give different return types to different versions, you can make the const and Non-const TextBlocks different processing:

std::cout<<tb[0];   No problem, read a non-consttb[0] = ' x ';    No problem, write a non-conststd::cout<<ctb[0];    . No problem, read a constctb[0] = ' x ';    Error, write a const

The reason for the error is an attempt to perform an assignment on a const char& "returned by the operator[of the const version".

Note here that the return type of Non-const operator[] is a reference to char (reference char type), not a char,

otherwise tb[0] = ' x ' will not compile.


For member functions If there is a const meaning there are two genres: bitwise AND logical

--bitwise Const Camp

Pursue: A member function can be said to be const only if you do not change any of the member variables of the object (except static). This means that it does not change any bit (bit) within the object.

Pros: It's easy to detect a breach, and the compiler just needs to look for the assignment of the member variable.

Disadvantage: Unfortunately, many member functions can pass bitwise tests, although they are not fully const in nature.

You can look at the following example:

Const Ctextblock CCTB ("Hello"); char* pc = &cctb[0];*pc = ' J ';

So CCTB now stores the content "Jello", which is clearly not in accordance with the definition of const


--logical Const Camp

Pursue: A const member function modifies some bits within the object it is processing, but only if the client is not able to monitor it.

For example, your Ctextblock class might have the length of the cache text chunk to ask:

Class Ctextblock{public: ...    std::size_t Length () const;private:    char* ptext;    std::size_t textlength;<span style= "White-space:pre" ></span>//the last computed text chunk length.    bool Lengthisvalid;<span style= "White-space:pre" ></span>//the current length is valid};std::size_t CTextBlock:: Length () const{    if (!lengthisvalid)   {        textLength = Std::strlen (ptext); <span style= "White-space:pre" ></span>//Error! The const member function cannot be assigned a value to both        Lengthisvalid = true;    }    return textLength;}

The length implementation is certainly not bitwise const, because both TextLength and lengthisvalid can be modified. They are both modified to be acceptable to the Const Ctextblock object, but the compiler does not agree.

So use a mutable (variable) to solve, use mutable to release the non-static member variable bitwise constness CONSTRAINTS

Class Ctextblock{public: ...    std::size_t Length () const;private:    char* ptext;    Mutable std::size_t textlength;//These member variables    can change lengthisvalid;//};std::size_t even within the mutable bool Ctextblock Const member function: : Length () const{    if (!lengthisvalid)   {        textLength = Std::strlen (ptext);//Now it can be        lengthisvalid = true;    }    return textLength;}

So avoid duplication in the const and NON-CONST member functions

This problem is caused by the above problem, although mutable can solve the problem of variables, but if this thing is very long,

We're going to need some two long, long monsters, so scary!.

This requires Non-const to invoke the const thing to avoid duplication, which makes it easier to change

{

Why not let const call Non-const?

Please, the const member function promises to never change the logical state of its objects, Non-const no

}


This requires invoking the concept of transformation, as shown in the following example:

Class Textblock{public:...const char& operator[] (std::size_t position) Const{.........return text[position];} char& operator[] (std::size_t position) {returnconst_cast<char&> (Static_cast<const TextBlock& > (*this) [position]);} ...};

Two transformations are used here:

Static_cast converting Non-const objects to const objects

Const_cast Removing a const


Conclusion:

Const is a very wonderful and extraordinary thing,

It can be used on pointers and iterators;

In pointers, iterators, and reference-related objects;

On the function parameter and return type;

In the local variable body;

On the member function,

Wait a minute....


Please remember:

<1> declaring something as const can help the compiler detect incorrect usage. A const can be applied to objects, function arguments, function return types, and member function bodies within any scope.

The <2> compiler enforces bitwise constness, but you should use conceptual constness (the conceptual constants) when you write your program.

<3> when the const and NON-CONST member functions have a substantially equivalent implementation, the NON-CONST version can be used to avoid code duplication with the const version.



*************************************** Reprint Please specify the Source: Http://blog.csdn.net/lttree ********************************************

"Effective C + +" study notes-clause 03

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.