Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use const, volatile and mutable keywords in C++

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use const, volatile and mutable keywords in C++. It is very detailed and has a certain reference value. Interested friends must finish reading it!

Basic use of const

I think this is a skill that must be mastered for a programmer who wants to be a good programmer in the future. Because there are a lot of articles about it written very well on the Internet, some of which I brought directly. Now let's take a look at its usage.

Const requires that the object it modifies is constant, cannot be changed, cannot be assigned, and cannot be used as a left value.

1. Modify the local variables in the function body.

Example:

Void func () {const int astat0;}

As a type qualifier, const has the same status as int.

Const int a; int const a

Is equivalent. So here we must clearly understand who the object modified by const is, whether an or intconst requires that the object modified by him is constant, can not be changed, cannot be assigned, and cannot be used as a l-value. So obviously it modifies a. This is a common way to use:

Const double pi=3.14

An error will occur if you attempt to assign or modify the pi later in the program. Then look at a slightly more complicated example.

Const int* p

Because int* p; and int* p; are equivalent. So const int (* p) and int const (* p) are equivalent. Now it's clear who const is embellishing. It's * p. So it's legal.

It's illegal because const embellishes you.

Int* const p; what does this mean?

See what const embellishes? It modifies p. But p is an int pointer, so there is no way to change the address of the pointer.

This is illegal * paired room1; / / this is legal

Let's take a more complex example, which is a combination of the above two.

Const int* const p; indicates that p itself is a constant, and the variable that p points to is also a constant. So

Illegal / illegal

Another function of const is to modify constant static strings. For example:

Const char* name=David

If there is no const, we may intentionally or unintentionally write statements like name [4] ='x', which will result in an assignment to the read-only memory area, and the program will immediately terminate abnormally. With const, this error can be detected as soon as the program is compiled, which is the advantage of const. Let logic errors be found at compile time.

2, modify the parameters when the function declaration for example void * myMemMove (void * dst,constvoid * src,intcount) this is the declaration of the memmove function I wrote, this function means (any type) copy the contents of * src to * dst, we now obviously see * src it only allows you to copy, you can not modify its value, so I am afraid that you will have problems in the definition of the function in the future and now limit you in the declaration.

3. Global variables our principle is still to use as few global variables as possible. Our second rule is to use const as much as possible. If a global variable is used only in this file, then the usage is no different from the function local variable mentioned earlier. If it is to be shared among multiple files, it involves a storage type problem.

There are two ways.

1. Use extern such as / * test.h * / extern const double pi;/* test.c * / const double pi=3.14

And then others that need to use the variable pi include test.h

# include test.h

Or, just copy that statement yourself.

As a result, after the whole program is linked, all those who need to use the variable pi share a storage area.

two。 Using static, static external storage classes

/ * constant.h * / static const pi=3.14

This header file must be included in the * .c file that needs to use this variable.

There must be no less static in front of you. Otherwise, the link will report that the variable has been defined multiple times. As a result, every * .c file that contains constant.h has its own copy for the variable, which is actually defined multiple times and takes up multiple storage space, but the conflict of redefinition between files is resolved by adding the static keyword. The downside is that storage space is wasted, resulting in larger executables after linking. But usually, this, a few bytes of change, is not a problem. The advantage is that you don't have to care about the file in which the variable is initialized. In fact, const, I think programmers are more likely to limit themselves and tell themselves where they can't go wrong.

Give me an example.

# include#includeint main () {int * ptransConst int a = 0 p = & a politic p = 3 politic printf ("a =% d\ n", a); system ("pause"); return 0;}

Now look at the results of the operation.

Now I'm going to talk about some of the more coquettish practices in a const operation.

For example, in a class we wrote before, we would use operator [] to return a point to reference, which we would normally write a

Const will also write a non-const opeartor []. This is one of our most common codes:

T & operator [] (int position) {return xxx [position];} const T & operator [] (int position) const {return xxx [position];}

This is the primary code we usually write, but now when we want to write an opeartor [] in TextBlock, it not only returns a referencr, but also performs boundary checking, log access information, data integrity check, and so on. At this time, when you implement operator [] const and operator [] () const, most of the two codes are the same, which is accompanied by code duplication and longer compilation time. Maintenance code expansion and other headaches. Of course, you can have the above cumbersome functions all encapsulated in other functions, and then call them in operator [] () and operator [] () const respectively, but you also said that you repeated some code, such as two return statements, function calls. What you really need to do is implement the function of operator [] once and use it twice. That is, you only need to write one function to make the other call this, which prompts us to transfer the constants. Next to witness the miracle, let's take a look at how the following code does the above:

Class TextBlock {public:... Const char& operator [] (std::size_t position) const {... Return text [position];} char& operator [] (std::size_t position) {return const_cast (static_cast (* this) [position]);}}

Take a closer look at this operation; return const_cast (static_cast (* this) [position]); first cast * this to const TextBlock, then call const's operator [], and finally cancel the const constant of the return value of const's operator [], and then return a non-const value. The call here is so wonderful that we can think about it and think about the meaning here. But some people will say, why not use const operator [] to call operator [], which forces both to work. It is wrong to think so!

It is not your job to make the const version call the no-const version to avoid repetition. Remember that the promise of the function modified by const is that I will never modify you. The no-const function does not have such a promise, so it is unrealistic for you to let a const function call a no-const function. In fact, over const has a lot of attributes that can be played with, as long as we think of it, we can implement it. Here is such an ok. Next let's take a look at the other two keywords.

Mutable keyword in C++

Mutalbe means "variable, changeable" in Chinese and is the opposite of constant (const in C++).

In C++, mutable is also set to break through the restrictions of const. Variables modified by mutable will always be in a mutable state, even in a const function.

We know that one of the important functions of functions modified by the const keyword is to protect member variables in the class. That is, this function can use all member variables in the class, but cannot modify their values. However, in some special cases, we still need to modify some member variables of the class in the const function, because the member variables to be modified have little to do with the class itself, and even if it is modified, it will not have much impact on the class. Of course, you can say, you can remove the const keyword of this function! But the problem is, I just want to modify one member variable, and the rest of the member variables still want to be protected by const.

Classic application scenarios such as: I want to test the number of times a method is called.

Class Person {public: Person (); ~ Person (); int getAge () const; / * call method * / int getCallingTimes () const; / * get how many times the above getAge () method has been called * / private: int age; char * name; float score; int mnums; / * for counting the number of times * /}

The most common practice is to add + 1 to the m_nums variable in the body of the getAge () method, but the getAge () method is also a const method, so you can't modify the m_nums variable. I don't want to remove the const keyword to allow others to modify member variables such as age. At this time, the mutable keyword comes in handy:

# include class Person {public: Person (); ~ Person (); int getAge () const; / * call method * / int getCallingTimes () const; / * get how many times the above getAge () method has been called * / private: int age; char * name; float score; mutable int mnums; / * for counting times * /}; Person::Person () {m_nums = 0;} Person::~Person () {} int Person::getAge () const {std::cout

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report