Usage of _ declspec in c ++

Source: Internet
Author: User
Usage of _ declspec in c ++

Syntax description:

_ Declspec (extended-decl-modifier-seq)

Extension modifier:

1: align (#)

Use _ declspec (align (#) to precisely control the alignment of user-defined data. # Is the alignment value.

E. g

_ Declspec (align (32 ))
Struct Str1 {
Int a, B, c, d, e;
};

[Turn] It is a sibling with # pragma pack (). The former specifies the minimum alignment value, and the latter specifies the maximum alignment value. When this occurs simultaneously, the former has a high priority. _ Declspec (align () is characterized,
It only specifies the Data Alignment position, but does not specify the actual memory length occupied by the data. When the specified data is placed at a specified position, the subsequent data filling is still performed in the way specified by # pragma pack. the actual size of the class/structure and memory pattern rules are as follows: before _ declspec (align (), data is filled in the way specified by # pragma pack, as described above. When
When _ declspec (align () is encountered, first find the alignment point closest to the current offset (the alignment length is max (the data length, the specified value )), then, extract the specified data type from this
Point to start filling, and the data type after it starts from behind it, still fill according to # pragma pack until the next _ declspec (align () is encountered ()). When all data is filled
The homogeneous value is compared with the value specified by _ declspec (align (). The larger value is used as the alignment length of the entire structure. In particular, when the value specified by _ declspec (align () is smaller than the corresponding type Length
This parameter does not work.
2: allocate ("segname ")
Use _ declspec (allocate ("segname") to declare a data item that has been allocated a data segment. It is used with code_seg, const_seg, data_seg, section, and init_seg of # pragma. segname must have these declarations.

E. g
# Pragma data_seg ("pai_data ")
Int a = 0;
Int B;
# Pragma data_seg () _ declspec (allocate ("pai_data") int c = 1;
_ Declspec (allocate ("pai_data") int D;
3. deprecated
Use _ declspec (deprecated) to describe a function, type, or other identifier that is no longer supported in new or future versions. You should not use this function or type. It works the same as # pragma deprecated.

E. g
# Define my_text "function is deprecated"
Void func1 (void ){}
_ Declspec (Deprecated) void func1 (INT) {printf ("func1n ");}
_ Declspec (deprecated ("** this is a deprecated function **") void func2 (INT) {printf ("func2n ");}
_ Declspec (deprecated (my_text) void func3 (INT) {printf ("func3 ");}
Int main ()
{
Fun1 ();
Fun2 ();
Fun3 ();
}
4. dllimport and dllexport

Use _ declspec (dllexport) ,__ declspec (dllimport) to explicitly define the dll interface to call its exe or dll file. Functions Defined with dllexport no longer need (. def) file declares these function interfaces. Note: If the template class is defined in the dll, it has implicitly implemented the two declarations. We only need to instantiate the class during the call.

In e. g conventional DLL
Class ___ declspec (dllexport)
Testdll {
Testdll (){};
~ Testdll (){};
};

Call the declaration in the client
# Import comment (Lib, "**. Lib)
Class ___ declspec (dllimportt)
Testdll {
Testdll (){};
~ Testdll (){};
};

E. g template class: dll
Template <class t>
Class test {
Test (){};
~ Test (){};
}
Call the declaration in the client
Int main ()
{
Test <int> B;
Return 0;
}
5. jitintrinsic

Use _ declspec (jitintrinsic) to mark a function or element as running in 64-bit common language. The specific usage is not seen.
6. _ declspec (naked)

For functions that do not use the naked declaration, the compiler generally saves the field (when entering the function, the compiler generates code to save ESI, EDI, EBX, and EBP registers -- prolog) and clear the on-site (when the function is exited, the code will generate the content of the Code to restore these registers-epilog) Code. For functions declared with naked, this code is generally not generated, this attribute is very useful for writing device drivers. We can write such a process by ourselves. It only supports x86. Naked is valid only for functions, but does not apply to type definitions. The _ forceinline keyword is instantly used for an inline function that cannot be generated for a function that marks naked.

E. g _ declspec (naked) func ()
{
Int I;
Int j;
_ Asm/* prolog */
{
Push ebp
Mov ebp, esp
Sub esp, _ LOCAL_SIZE
}
/* Function body */
_ Asm/* epilog */
{
Mov esp, ebp
Pop ebp
Ret
}
}
7. restrict and noalias

_ Declspec (restrict) and _ declspec (noalias) are used to improve program performance and optimize programs. These two keywords are only used for functions. Restrict is used for the function to return pointers. Restrict indicates that the function return value is not converted to an alias, and the returned pointer is unique and not blurred by the alias of other function pointers, that is to say, the returned pointer has not been used and is unique. The compiler usually checks whether the pointer is available, whether it is alias, and whether it is in use. When this keyword is used, the compiler will not check the information. Noalias means that the function call cannot modify or reference the visible global state and only modifies the memory directly pointed to by the pointer parameter. If a function specifies the noalias keyword, the optimizer determines that, in addition to the inherent parameters, only the first level of the parameter pointer is indirectly referenced or modified within the function. Visible Global States refer to all datasets that are not defined or referenced outside the encoding range. The encoding range refers to all source files or a single source file. In fact, these two keywords provide a guarantee for the compiler, so that the compiler will trust him to not perform some check operations.

E. g
# Include <stdio. h>
# Include <stdlib. h>
# Define M 800 # define N 600 # define P 700 float * mempool, * memptr;
_ Declspec (restrict) float * ma (int size)
{
Float * retval;
Retval = memptr;
Memptr + = size;
Return retval;
}
_ Declspec (restrict) float * init (int m, int n)
{
Float *;
Int I, j;
Int k = 1;
A = ma (m * n );
If (! A) exit (1 );
For (I = 0; I <m; I ++)
For (j = 0; j <n; j ++)
A [I * n + j] = 0.1/k ++;
Return;
}
_ Declspec (noalias) void multiply (float * a, float * B, float * c)
{
Int I, j, k;
For (j = 0; j <P; j ++)
For (I = 0; I <M; I ++)
For (k = 0; k <N; k ++)
C [I * P + j] = a [I * N + k] * B [k * P + j];
}

Int main ()
{
Float * a, * B, * c;
Mempool = (float *) malloc (sizeof (float) * (M * N + N * P + M * P ));
If (! Mempool)
Puts ("ERROR: Malloc returned null"); exit (1 );
Memptr = mempool;
A = init (M, N );
B = init (N, P );
C = init (M, P );
Multiply (A, B, C );
}
8. noinline _ declspec (noinline)

Tells the compiler not to inline a specific function.
9. noreturn _ declspec (noreturn)

Tells the compiler that no return value is returned. Note that adding _ declspec (noreturn) to a function that does not want to return will result in no definition error.

10. nothrow _ declspec (nothrow)

It is used for function declaration and tells the compiler function not to throw an exception.

E. g
# Define winapi _ declspec (nothrow) _ stdcall
Void winapi F1 ();
Void _ declspec (nothrow) _ stdcall F2 ();
Void _ stdcall F3 () Throw ();
11. novtable _ declspec (novtable)

It is used for the declaration of any class, but only for the pure Virtual Interface Class. Therefore, such a statement cannot be used by its own instance. it prevents the compiler from initializing the virtual table pointer when constructing and destructor, which will remove references to the virtual table associated with the class. if you try to instantiate a class with the novtable keyword, it will cause the AV (access violation) error. the defect of virtual in C ++ is that vtable will increase the size of the Code. This keyword can be used to reduce the size of the code when the class or pure Virtual Interface does not need to be instantiated.

E. g
# If _ msc_ver> = 1100 &&! Defined (_ Debug)
# Define afx_novtable _ declspec (novtable)
# Else
# Define afx_novtable
# Endif
....
Class afx_novtable cobject
{
...
};
This is a piece of code in VC. We can see that when the release version is compiled, it is _ declspec (novtable) before cobject, and there is no such restriction in the debug version.

E. g
# Include <stdio. h>
Struct _ declspec (novtable) x
{
Virtual void MF ();
};
Struct Y: Public x
{
Void mf ()
{
Printf_s ("In Yn ");
}
};
12. Functions of selectany)

_ Declspec (selectany) allows us to initialize a global variable in the. h file instead of placing it in. cpp. For example, if there is a class with a static variable, then we can. h uses code like "_ declspec (selectany) type class: Variable = value;" to initialize this global variable. This. H is included multiple times, and the linker also removes multiple definition Errors for us. What are the advantages of this? I think it will be much more convenient for teamplate programming.

E. g
Class test
{
Public:
Static int t;
};
_ Declspec (selectany) int test: t = 0;
13. Thread

The prefix used to declare a local variable of a thread. _ declspec (thread) is a modifier that Microsoft adds to the Visual C ++ compiler. It tells the compiler that the corresponding variables should be placed in its own section in the executable or DLL file. The variables after _ declspec (thread) must be declared as a global or static variable in the function (or outside the function. You cannot declare a local variable of Type _ declspec (thread.

E. g
_ Declspec (thread)
Class X {
Public:
Int I;
} X; // x is a thread objectX y; // y is not a thread object

14. uuid _ declspec (UUID)

It is used by the compiler to associate a guid with a declaration or definition of a class or structure with a uuid attribute.

E. gstruct _ declspec (uuid ("00000000-0000-0000-c000-000000000046") IUnknown; struct _ declspec (uuid ("{specification}") IDispatch; you can view the source code in MFC. :)

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.