C ++ using the modifier summary

C ++ using the modifier summary

Basic type modifiers

C ++ allows the char, int and double placing a modifier, and other basic data types. Basic types commonly used modifiers are:

  • signed

  • unsigned

  • long

  • short

Modifiers signed, unsigned, long and short applicable integers, Signed and unsigned applicable char, Long may be applied to double.

Modifiers signed and unsigned may be as long or short prefix modifiers. For example: unsigned int Long .

C ++ allows shorthand notation to declare an unsigned short integer , or an unsigned long integer . You can not write int, just write the word unsigned, short , or unsigned, Long , int is implied. For example, the following two statements both declare unsigned integer variables.

unsigned x;
// 等价于
unsigned int y;

C ++ Explain the difference between signed integer and unsigned integer modifiers:

#include <iostream>
using namespace std;

int main()
{
   short int i;           // 有符号短整数
   short unsigned int j;  // 无符号短整数
   j = 50000;
   i = j;
   cout << i << " " << j;
   return 0;
}

operation result

-15536 50000

For there is no sign of bits into operation symbol, take N 2 n N-2^n calculation method, depending on the defined data types nint, short, char, long intand the like, N being unsigned values, such as the text of the N = 50000, short 16-bit, calculated as 50000 2 1 6 50000-2^16 obtained -15536.

Limited modifier

const type

const object types can not be modified during program execution. After c ++ defined by a constant const, and writes the symbol table (Symbol Table) , making it a compile-time constant, not allocate storage, nor the memory storing the read operation, such that it efficiency is very high.

volatile type

Qualifier volatile tells the compiler does not require optimization variables declared volatile, ** so that the program can be read directly from memory variables. ** optimized for variable compilers will generally variable, the variable value in the memory register to speed up the write efficiency.

When you want to read the value of volatile declared variables, the system always re-read data memory from which it is , even if it had just read in front of the command data, not the value from the register, but from memory read the data. volatile can guarantee stable access to a specific address.

Note that in VC 6, a general debug mode no code optimization, so the effect of this keyword can not see.

By inserting the following assembly code to test for the volatile keyword, the final impact of the program code, enter the following code:

#include <stdio.h>
void main()
{
    int i = 10;
    int a = i;
    printf("i = %d", a);
 
    // 下面汇编语句的作用就是改变内存中 i 的值
    // 但是又不让编译器知道
    __asm {
        mov dword ptr [ebp-4], 20h
    }
    int b = i;
    printf("i = %d", b);
}

Then, in Debug mode version of the program, the output results are as follows:

i = 10
i = 32

In Release mode version of the program, the output results are as follows:

i = 10
i = 10

The results clearly show the output, Release mode, the compiler for code optimization, the second is not output the correct value of i. Below, we declare i plus the volatile keyword, and see what happens:

#include <stdio.h>
void main()
{
    volatile int i = 10;
    int a = i;

    printf("i = %d", a);
    __asm {
        mov dword ptr [ebp-4], 20h
    }
    int b = i;
    printf("i = %d", b);
}

Respectively in Debug and Release versions run the program, the output is:

i = 10
i = 32

In general, volatile in several places with the following:

  • Variables for other programs detected the interrupt service routine changes need to add volatile;
  • Multitasking environment shared among tasks is a sign should be added volatile;
  • Memory mapped registers usually have added volatile hardware description, because each of its different reading and writing may sense;

volatile pointer

Const modifier and similar words, const have constant pointers and pointer constant argument, volatile there is a corresponding concept:

Pointer constant : Modified objects pointed to by the pointer , the data is volatile or const:

const char* cpch;
volatile char* vpch;

Note: For VC, this feature is achieved after VC 8 is safe.

Constant pointer : a pointer value itself - an integer variable representing the address, of a volatile or const:

char* const pchc;
char* volatile pchv;

note:

  • It can be assigned to a non-volatile int volatile int, but not the non-volatile object is assigned to a volatile object.
  • In addition to the basic types of user-defined type may also be modified with a volatile type.
  • In a C ++ class identifier volatile it can only access a subset of the interface, controlled by a subset of the class implementor. Users can only use const_cast to gain full access to the type of interface. In addition, volatile as the const passed from class to its members.

volatile multi-threaded

Some variables are declared with the volatile keyword. ** When the two threads to be used in a particular variable and the value of the variable will be changed, it should be declared with volatile, the key role is to prevent the compiler to optimize the variable from memory into the CPU registers. ** maintain data consistency, Case:

volatile  BOOL  bStop  =  FALSE;

(1) In a thread:

while(  !bStop  )  {  
    // ...  
}  
bStop  =  FALSE;  
return;    

(2) in another thread, the upper thread loop to be terminated:

bStop  =  TRUE;  
while(  bStop  );  //等待上面的线程终止,如果bStop不使用volatile申明,那么这个循环将是一个死循环,因为bStop已经读取到了寄存器中,寄存器中bStop的值永远不会变成FALSE,加上volatile,程序在执行时,每次均从内存中读出bStop的值,就不会死循环了。

This keyword is used to set the storage location of an object in memory, not registers. Because the general object compiler might copy thereof in registers to accelerate the speed of execution of instructions, code segments for example:

// ...  
int  nMyCounter  =  0;  
for(;  nMyCounter<100;nMyCounter++)  
{  
	// ...  
}  
// ...

In this code, the copy may nMyCounter stored into a register (cycle testing and operation of nMyCounter always register values for this), but there are additional segments of code executes such an operation: nMyCounter - = 1; this operation is to change nMyCounter nMyCounter memory operation, so there is such a phenomenon: nMyCounter variations are not synchronized.

restrict the type of

By the restrict modified pointer is the only way to access the object it points to. Only C99 adds a new type qualifier restrict. Mainly used to modify a pointer to the memory can not be referenced another pointer.

Only by the other pointer or a pointer based on the pointer operation, i.e., limiting access to the object with a pointer to the limitations restrict only be accessed through this pointer, optimizing compiler which is very good.

Class access modifier

The data package is an important feature of object-oriented programming, which prevents direct access to the internal member function of class type. Access is restricted by the members of each class within the body region marked public, private, protected to specify.

class Base {
   public:
  // 公有成员
 
   protected:
  // 受保护成员
 
   private:
  // 私有成员
};
  • Public (public) members : a program outside of class is accessible. You can not use any member functions to set and get the value of public variable.
  • Private (private) members : private variables or private functions in an external class is inaccessible, even impossible to see. Only classes and friend functions can access private members. By default, all members of the class are private.
  • Protection (protected) members : protection or protection functions and variables private members are very similar, with one exception, to protect members of the derived class (ie subclasses) are accessible.

explicit qualifier

C ++ provides keyword explicit, only a single parameter class constructor for modifying, it is the effect that it is a constructor, rather than implicit, another keyword corresponding to the Implicit saying, means hidden default constructor class that is declared as implicit (implicit).

In C ++, a constructor parameter (or in addition to the first parameter the other parameters have default values ​​of the multi-argument constructor), assume two roles. 1 is a constructor, and 2 is the default implicit type conversion operator.

So, sometimes we wrote as AAA = XXX, such code, and just happens to be the type XXX AAA single-argument constructor parameter types, this time the compiler will automatically call the constructor, create an AAA object.

It looks as if the cool, very convenient. However, in some cases (see example below authoritative), but contrary to our (programmer) intention. This time we should in front of the constructor add explicit modification, this constructor can only be specified explicitly call / use, not as a type conversion operator is implicitly use.

class Test1
{
    public:
    Test1(int n)
    {
        num=n;
    }//普通构造函数
    private:
    int num;
};
class Test2
{
    public:
    explicit Test2(int n)
    {
        num=n;
    }//explicit(显式)构造函数
    private:
    int num;
};

int main()
{
    Test1 t1=12;//隐式调用其构造函数,成功
    Test2 t2=12;//编译错误,不能隐式调用其构造函数
    Test2 t2(12);//显式调用成功
    return 0;
}

General constructor can be implicitly called. The explicit constructor can only be invoked explicitly.

Storage class modifier

** defined storage class C ++ program variables / functions range (visibility) and life cycle. ** These specifiers placed before the modified type thereof. The following list storage class C ++ programs are available:

  • auto
  • register
  • static
  • external
  • mutable
  • thread_local (C++11)

C ++ start from 17, auto key is not stored C ++ class specifier and the register keyword is deprecated.

auto storage class

Since ++ 11 C, Auto keywords used in two cases: the variable type is automatically inferred from the initialization expression when declaring a variable, the function returns the placeholder value function declaration.

C ++ 98 standard auto keyword is used to declare an automatic variable, but the use of minimal and unnecessary, this usage has been removed in C ++ 11.

The initialization expression variable is declared automatically infer the type, such as:

auto f=3.14;      //double
auto s("hello");  //const char*
auto z = new auto(9); // int*
auto x1 = 5, x2 = 5.0, x3='r';//错误,必须是初始化为同一类型

register storage class

register stored in the register class is used instead of a local variable definitions are stored in RAM. This means that a maximum size equal to the size of the variable register (typically a word), and it is not a unary '&' operator (because it has no memory location).

{
   register int  miles;
}

Register only for variables that need quick access to, such as counter. It should also be noted that the definition of 'register' means that the variable is not stored in the register, it means that the variable may be stored in registers, depending on the hardware limitations and implementation.

static storage class

static storage class instructs the compiler to keep the existence of local variables within the lifetime of the program, without the need to be created and destroyed every time it enters and leaves scope. Thus, using a modified static local variables can be maintained between the values of local variables in the function call.

static modifier can be applied to global variables. When the static modification of global variables, variable scope will limit within which it is declared in the file.

extern storage class

extern storage class is used to provide a reference to a global variable, the global variable for all the program files are visible. When you use 'extern', for the variables can not be initialized, it will point to a previously defined variable names over the storage location.

When you have multiple documents and define a global variable or function that can be used in other documents, you can use in other documents extern to get a variable or function defined reference. It can be understood, extern is used to declare a global variable or function in another file.

extern modifier is usually used when there are two or more files share the same global variable or a function of the time

mutable storage class

mutable specifier applies only to object class, object member allows alternative constant. That is, mutable member can be modified by const member functions.

thread_local storage class

Use thread_local explanatory variable declarations can only be accessed on the thread it was created on it. Variables are created when a thread is created, and destroyed when destroying threads. Each thread has its own copy of the variable.

thread_local specifiers may be combined with static or extern.

thread_local may be applied to only the data declarations and definitions, thread_local function declaration or definition can not be used.

The following presentation may be declared as a variable thread_local of:

thread_local int x;  // 命名空间下的全局变量
class X
{
    static thread_local std::string s; // 类的static成员变量
};
static thread_local std::string X::s;  // X::s 是需要定义的
 
void foo()
{
    thread_local std::vector<int> v;  // 本地变量
}

Reference material

C ++ modifier type
C / C ++ Detailed in the volatile keyword
in C ++ restrict the role of modifier
C ++ class access modifiers
C ++ storage class

Released five original articles · won praise 0 · Views 56

Guess you like

Origin blog.csdn.net/taokexia/article/details/105360820