Reputation: 523
I'm learning C++ from "C++ for Programmers" book. In "templates" section, there is a code like that:
template<typename T>
void printArray(const T * const array, int size)
{
for (int i = 0; i < size; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
My question is, the constants of first parameter in function. I have never seen two constants in one parameter. I tried to realize but I could not. Thanks for helps.
Upvotes: 1
Views: 112
Reputation: 76240
const T * const
means: a constant pointer to a constant T. Which means that both the pointer and the T
pointed are constant.
A good rule for reading this kind of parameters is to read it right to left.
Upvotes: 4
Reputation: 18252
In your example, you have a const
pointer to a const
object of type T
. This means you can't change where the pointer is pointing or the object to which it points.
You can actually have const in even more places in a single line. Take this declaration for example:
class MyClass {
public:
const std::string& get_name(const int * const id) const;
};
In this case, the function get_name
is constant, and can't modify the instance of MyClass
. It takes in a constant pointer to a constant integer, and returns a constant reference to a string.
If you'd like to learn more about best practices while using const
(and other parts of C++), I highly recommend Bruce Eckel's book Effective C++: 55 Specific Ways to Improve Your Programs and Designs.
Upvotes: 1
Reputation: 15934
The syntax just tells you that there is a pointer that is const and the thing it points to is also const.
For more reading I would recommend you have a look at:
http://www.parashift.com/c++-faq/const-ptr-vs-ptr-const.html
http://www.parashift.com/c++-faq/const-correctness.html
Upvotes: 0