What exactly does the const
keyword in C++ mean when it's written at the end of a member function (after the argument list)?
It means that *this
is const
inside that member function, i.e. it doesn't alter the object.
The keyword
this
is a prvalue expression whose value is the address of the object for which the function is called. The type ofthis
in a member function of a classX
isX*
. If the member function is declaredconst
, the type ofthis
isconst X*
. [section 9.3.2 §1]In a
const
member function, the object for which the function is called is accessed through aconst
access path; therefore, aconst
member function shall not modify the object and its non-static data members. [section 9.3.2 §2]
This means that a const
member function can be called on a const
instance of the class. A non-const
member function can't be called on [1]a const
object, since it could potentially try to modify it.
[1] Note: a temporary is not a const
object unless it's of const
type.
const
at the end of a function signature means that the function should assume the object of which it is a member is const
. In practical terms it means that you ask the compiler to check that the member function does not change the object data in any way. It means asking the compiler to check that it doesn't directly change any member data, and it doesn't call any function that itself does not guarantee that it won't change the object.
When you create a const
object you are asking the compiler to make sure that that object does not change beyond its initialization. That in turns means that the compiler will check you don't directly change its member data and that you don't call any function that does not guarantee it won't change the object.
This is all part of the const correctness philosophy. In essence it means that if things work right now and they won't change then they will never break. In other words, constant things are easier to work with reliably. This const
thing at the end of function signatures is a tool for you to prohibit things from breaking. This in turns means you should put const
everywhere you possibly can.
Compiler optimizations are possible, but the main benefit is in enforcing the contract expressed in the function's declaration - if you define a member function as const
, the compiler prevents any modification to the object inside that function.
You can exempt individual fields in the class from this restriction using mutable
in their declaration. This is useful for example when you have a class that encapsulates its own lock_guard, which must change its value to enforce thread safety even within const
member functions.
精彩评论