Sometimes when reading about C++, for instance about template argument deduction, the term “top-level cv-qualifiers” comes up. I just spent an unreasonable amount of time being puzzled by something because I didn’t understand that references don’t have top-level cv-qualifiers. This post will hopefully help the next person (hi, next-year Anders) not make the same mistake.
Looking at
const int&
, I assumed without even thinking about it that the const
here was the top-level one. It is not.
First, what’s a cv-qualifier? It’s const
, volatile
or both. Let’s just use const
as an example for this article.
Then, what’s a top-level cv-qualifier
? The best way to explain is with an example, and the best example is a pointer. There are two levels of constness to a pointer, the constness of the pointer itself, and the constness of what it’s pointing to.
Given const int *
, a non-const pointer to const int, we can visualise it as
pointer (the * part) |
to |
const int (the const int part) |
And given const int * const
, a const pointer to const int, we can visualise it as
const pointer (the * const part) |
to |
const int (the const int part) |
(And so on, you can imagine how it looks for pointers to non-const int
.) The top-level cv-qualifier is the one on the top level, the cv-qualifier on the pointer itself.
Now, how does this look for references?
Given const int&
, a reference to const int, we can visualise it as
reference (the & part) |
to |
const int (the const int part) |
But there’s no such thing as a const reference! Constness applies to the object itself, and a reference is not an object, just an alternative name for an existing object. So there is no such thing as a const int& const
, i.e. there’s no such thing as
const reference (the & const part) |
to |
const int (the const int part) |
Which means, references don’t have top-level cv-qualifiers. The standard even has an example:
Example: The type corresponding to the type-id
[basic.type.qualifier]const int&
has no top-level cv-qualifiers.
This is by the way a somewhat recent addition, until this Core Language Defect Report was resolved in 2014, the term “top-level cv-qualifier” was never actually defined in the standard.