What is the meaning of a constant at the end of a member function?

What exactly does the const keyword mean in C ++ when it is written at the end of a member function (after a list of arguments)?

+54
c ++ c ++ - faq const
30 Oct '10 at 17:52
source share
3 answers

This means that *this const inside this member function, i.e. does not modify the object.

The this is a prvalue expression whose value is the address of the object for which the function is being called. The type this in a member function of class X is equal to X* . If a member function is declared const, this type is const X* . [section 9.3.2 ยง1]

In a member function const object for which the function is called is accessed via the const access path; therefore, the const member function must not modify the object and its non-static data elements. [section 9.3.2 ยง2]

This means that the const member function can be called on an instance of the const class. A member element not const cannot be called into object [1] a const , since it can potentially try to change it.

[1] Note: a temporary object is not const if it is not of type const .

+60
Oct 30 '10 at 17:53
source share

const at the end of a function signature means that the function must accept an object of which it is a member. In practice, this means that you ask the compiler to verify that the member function is not modifying the object data in any way. This means that the compiler must verify that it does not directly modify the data of the element, and does not call any function that does not guarantee itself that it will not change the object.

When you create a const object, you ask the compiler to make sure that this object has not changed beyond its initialization. This in turn means that the compiler verifies that you are not directly modifying its member data, and that you are not calling any function that does not guarantee that it will not modify the object.

This is all part of the philosophy of const correct . In essence, this means that if everything works right now, and they do not change, they will never break. In other words, persistent things are easier to work with reliability. This const thing at the end of function signatures is a tool that allows you to prohibit broadcasting. This in turn means that you should put const wherever possible.

+24
Oct 30 '10 at 18:16
source share

Compiler optimization is possible, but the main advantage is the execution of the contract, expressed in the function declaration - if you define a member function as const , the compiler prevents any modification of the object inside this function.

You can free individual fields in a class from this restriction by using mutable in your declaration. This is useful, for example, when you have a class that encapsulates its own lock_guard, which should change its value to ensure thread safety even inside const member functions.

+10
Oct 30 2018-10-10
source share



All Articles