C + + Const && define

Source: Internet
Author: User

This article records the contents of the Const keyword in C + +, divided into 3 parts, the difference between const and define, the role of Const, the use of Const.

The difference between const and define

The role of the const

    1. Const is used to define constants: The compiler can perform security checks on static data types.
    2. const modifier function Formal parameter: When the parameter is a custom type or abstract data type, you should change "value passing" to "Const & Pass" to improve efficiency as follows:

      void Fun (a a); inefficient, the function body produces a type of temporary object for copying parameter A, the construction, copying, and destruction process of the temporary object will consume time.

      void Fun (A const &a), highly efficient. Reference does not produce a temporary object, saving time, but the light reference may change the value of a, so add a const

    3. The return value of the const modifier function: For example, if the return value of a function that is passed by pointer is const, the return value cannot be directly modified, and the return value can only be assigned to a const-decorated pointer of the same type. As follows:

      const char *getchar () {}

      Char *ch = GetChar ();//error

      const char *ch = GetChar ();//correct

    4. Const-Decorated class member function (function definition body): Any function that does not modify the data member should be decorated with a const so that the compiler will error when the data member is accidentally modified or a non-const member function is called. int GetChar (void) const;

Instance code:

Summary: In the Declaration and definition of a class member function, a const function cannot modify its data member. Const object, cannot reference a non-const member function.

Use of const

C + + Const && define

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.