The Const and Constexpr in C++ (REMAKE)
I have written a post about const
in C++ in Chinese before, but it was too verbose and unclear. :( So, I decided to rewrite it.
BASIC USAGE OF CONST
MODIFIES BASIC DATE TYPE WITH CONST
The most basic usage of const
is to define a constant. A constant is a variable whose value cannot be changed after initialization.
1 | int a = 1; |
MODIFIES POINTERS WITH CONST
When it comes to pointers, const
can be used in two ways: top-level const and low-level const.
Top-level const means that the pointer itself is a constant, i.e. you can't change what it points to.
Low-level const means that the object that the pointer points to is a constant, i.e. you can't change the value of that object through this pointer.
For example:
1 | int x = 1; |
MODIFIES REFERENCE WITH CONST
For reference, there is only one way to use const
: const T &
(T is type name). Reference itself (like T &
) is always top-level, since you can't change what it refers to after its initialization. So, const T &
makes the reference both top-level and low-level.
MODIFIES OBJECTS WITH CONST
Modifying an object with const
means that this object is immutable after its initialization.
1 | const std::string str = "This is an immutable string."; |
CONST IN FUNCTIONS
CONST IN PARAMETER LIST
A parameter modified with const
means it is read-only to the function. Usually, we use this feature together with reference. So, when we don't want a function to change a specific argument, the parameter's type may look like const T &
.
1 |
|
THE CONST AFTER A MEMBER FUNCTION
The const after a member function indicates that the function does not modify any non-mutable data members of the class. In other words, this means that the this
pointer is const, implying that this member function does not alter the state of this object.
1 |
|
RETURNS A CONST
When returning an object, the const
before the return type indicates that this object is a constant and is immutable. For example: const int& GetAgeConst()
, which returns a rvalue whose referenced content cannot be modified.
When return a pointer type (or a reference), const
helps protect the pointer or reference content from being modified. For example: const char * const Fun()
, which returns a pointer to a constant, whose pointed content and the pointer itself cannot be modified.
Here is an example generated by new bing:
1 |
|
CONSTEXPR (NEW IN C++11)
constexpr
keyword helps the compiler find those constant expressions at compile stage. A really common place of use is defining an array:
1 |
|
To learn more, you may read Modern C++ Tutorial