There has been lots of questions/answers pertaining questions to constexpr expression but i have a question which is pretty close to other question but slightly different in another sense. Anyway here it goes.
#include <iostream>
using namespace std;
constexpr int x = 1; // TAG A
int main() {
constexpr int &xf = x; // TAG B error out
const int &xf1 = x; // TAG C works
constexpr int const &xf2 = x; // TAG D works
return 0;
}
Error:
Binding reference of type 'int' to value of type 'const int' drops 'const' qualifier [reference_bind_drops_quals]
Comments:
- TAG A clearly shows x is const int. Accordingly to the C++ Primer 5th Edition on page section 2.44 "Variables declared as constexpr are implicitly const and must be initialized by constant expressions:". So this is good.
- TAG B --> error message implies that the constexpr did not implicitly "const" the variable xf. Hence xf is int &. This contradict TAG A. Why?
- TAG C --> This is the usual reference to const
- TAG D --> Additional "const" added to make it a const reference due to how it behaves in TAG B.
Is there a difference in the word "reference to a const" and "const reference"?
it seems reference to const means reference is referring to a const object while not allowing to make modification while "const reference" is that the reference is const but it can point to either const or non-const objects.
This is one big confusing thing.
Aucun commentaire:
Enregistrer un commentaire