In-depth analysis of several of the most infrequently used keyword _c languages in C + +

Source: Internet
Author: User
Tags int size volatile
mutable keyword
Keyword mutable is an infrequently used keyword in C + +, and he can only be used for non-static and very data members of a class
We know that the state of an object is determined by the Non-static data members of that object, so as data members change,
The state of the image will change as well!
If a member function of a class is declared as a const type, it means that the function does not change the state of the object, i.e.
The function does not modify the Non-static data members of the class. But sometimes it is necessary to have the data members of the class in the class function
To assign a value. This time we need to use the mutable keyword.
For example:
Copy Code code as follows:

Class Demo
{
Public
Demo () {}
~demo () {}
Public
BOOL Getflag () const
{
m_naccess++;
return m_bflag;
}
Private
int m_naccess;
BOOL M_bflag;
};
int main ()
{
return 0;
}

Compiling the above code will cause error C2166:l-value specifies const object
Describes a non-static data member that changes a class in a const-type function.
This time you need to use mutable to modify the Non-static data members that you want to change in the const member function
M_naccess, the code is as follows:
Copy Code code as follows:

Class Demo
{
Public
Demo () {}
~demo () {}
Public
BOOL Getflag () const
{
m_naccess++;
return m_bflag;
}
Private
mutable int m_naccess;
BOOL M_bflag;
};
int main ()
{
return 0;
}

In this way, there will be no errors when recompiling!

volatile keyword
Volatile is a little-known keyword in c/s + +, which tells the compiler not to hold a temporary copy of a variable, which can be applied to the underlying type
such as: Int,char,long ... Also applies to C's structure and C + + classes. When using volatile modifications to a struct or class object, the structure or
All members of the class will be treated as volatile.
Using volatile does not negate the need for synchronization objects such as Critical_section,mutex,event
For example:
int i;
i = i + 3;
Anyway, there will always be a short time, I will be placed in a register, because arithmetic operations can only be done in registers. Generally speaking, volatitle
Keywords apply between rows and rows, not within a row.
Let's first implement a simple function to look at the deficiencies in the assembly code generated by the compiler and see how the volatile keyword corrects this shortcoming. There is a busy loop in the body of the function (the so-called busy loop is also called busy waits, a cyclic method that is highly wasteful of CPU time)
Copy Code code as follows:

void Getkey (char* pch)
{
while (*pch = 0)

}

When you turn off the optimization options in the VC development environment, compile the program and get the following results (assembly code)
Copy Code code as follows:

; while (*pch = 0)
$L 27
; Load the address stored in PCH
mov eax, DWORD PTR _PCH$[EBP]
; Load the character into the EAX register
movsx eax, BYTE PTR [EAX]
; Compare the value to zero
Test eax, EAX
; If not zero, exit loop
Jne $L 28

JMP $L 27
$L 28
;}

This code that does not optimize is constantly loading the appropriate address, loading the contents of the address, testing the results. The efficiency is fairly low, but the results are very accurate.
Now let's take a look at it. After all of the compiler's most optimized option switches are turned on, recompile the program, generate the assembly code, and the above code
Compare what's different
Copy Code code as follows:

; {
; Load the address stored in PCH
mov eax, DWORD PTR _pch$[esp-4]
; Load the character into the AL register
Movsx al, BYTE PTR [EAX]
; while (*pch = 0)
; Compare the value in the ' AL register to Zero
Test Al, AL
; If still zero, try again
Je Short $L 84

;}

As you can see from the length of the code, it is much shorter than the absence of optimization. Note that the compiler puts the MOV instruction out of the loop. This is a very good optimization in a single thread, but in a multithreaded application, if another thread changes the value of the variable, the loop never ends. The value of the test is always placed in the register, so the code in the case of multithreading, there is a huge bug. The workaround is to write the Getkey function again and declare the parameter PCH as volatile, as follows:
Copy Code code as follows:

void Getkey (volatile char* pch)
{
while (*pch = 0)

}

This modification has no effect on the most optimized version, please see the following optimization results:
Copy Code code as follows:

; {
; Load the address stored in PCH
mov eax, DWORD PTR _pch$[esp-4]
; while (*pch = 0)
$L 84:
; Directly compare the value to zero
CMP BYTE PTR [EAX], 0
; If still zero, try again
Je Short $L 84

;}

The result of this modification is perfect, the address will not change, so the address statement is moved outside the loop. The content of the address is volatile, so it is constantly being reviewed in each cycle.
It is legal to pass a const volatile variable as a parameter to a function. Such a declaration means that a function cannot change the value of a variable, but the value of a variable can be changed by another thread at any time.

explicit keyword
When we write an application, the explicit keyword is essentially rarely used, and its role is to "prohibit a single parameter constructor" from being used for automatic type conversion, where the typical example is the container type, in which you can pass the initial length as a parameter to the constructor.
For example:
You can declare such a constructor
Copy Code code as follows:

Class Array
{
Public
explicit Array (int size);
......
};

Here the explicit keyword plays a vital role, and if this keyword is not available, the constructor has the ability to convert int to array. Once this
When this happens, you can give an integer value to the tribe of the array without causing any problems, such as:
Array arr;
...
arr = 40;
At this point, the automatic type conversion of C + + converts 40 into an array with 40 elements and assigns it to the ARR variable, which is not the result we want.
We declare the constructor as explicit, and the assignment above will cause the compiler to make an error, so that we can find it in time.
It should be noted that explicit also prevents "initialization with transformational operations in assignment syntax";
For example:
Copy Code code as follows:

Array arr (40);//correct
Array arr = 40;//Error
Take a look at the following two types of actions:
x x;
Y y (x);//Explicit type conversions
Another kind
x x;
Y y = x;//implicit type conversions

There is a small difference between these two operations, the first way is to create a new object of type Y based on the type X by explicit type conversion, and the second method creates a new object of type Y through an implicit conversion.
Explicit keyword application is mainly described above the definition of the constructor, reference to the application of the keyword can look at the STL source code, which used a lot of this keyword

__based keyword
This keyword is primarily used to solve some of the problems associated with shared memory, and it allows pointers to be defined as 32-bit offset values starting at a certain point, rather than absolute position of memory species
As an example:
Copy Code code as follows:

typedef struct TAGDEMOSTRUCT {
int A;
Char sz[10];
} demostruct, * pdemostruct;
HANDLE hfilemapping = createfilemapping (...);
LPVOID Lpshare = (lpdword) mapviewoffile (...);
Demostruct __based (lpshare) * LPDEMO;

The above example declares a pointer Lpdemo, internally storing an offset value starting at Lpshare, that is, Lphead is an offset value based on Lpshare.
The demostruct of the above example is just a random structure defined to represent any structure.
Although __based pointers are easy to use, you have to pay a price for efficiency. Every time you handle data with a __based pointer, the CPU must add a base address to it to point to the real location.

Here I just introduced a few not very common keywords meaning that usage, other those common keywords introduced their article has been a lot of here
Will not be introduced. I hope that these content can be a certain help!

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.