See C + + (const attribute) with Assembly vision

Source: Internet
Author: User

Turn from: http://blog.csdn.net/feixiaoxing/article/details/6786622

Const is a key word in C + + language, but if used well, it can greatly improve the robustness of the code. In general, the use of const is still quite a lot of places, but mainly in the following areas: (1) The protection of ordinary variables, (2) The protection of address space, (3) the Declaration and protection of class initial variables, and (4) the protection of class variables in functions. The protection of const is primarily from the compiler level and is not related to the operation of the program.

(1) Protection of common variables

View plain const int data = 10;   const char str = ' a ';       Const double PI = 3.14; The code above is the definition of a set of global variables, and if the variable changes in the function, the code fails to compile.


(2) Protection of address space

View plain void process () {int value = 10;   Const int* Address = &value; Unlike the code above, this is where the code will fail if the value that the address points to is changed. You can add *address = 100 before the end of the function; try it.


(3) The definition of a class const member variable

View Plain class Desk {const int price;       Public:desk ():p rice () {} ~desk () {}}; A const member variable is a const keyword that is added before a class variable is defined. Unlike ordinary member variables, the const variable must be initialized in the constructor. If there is no const keyword, then it is not necessary to initialize it within the constructor.


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.