Reference to a constant pointer?

Suppose you have the following declarations:
int x = 5;
int *const ptr2 = &x;
const int*& p_ref2 = ptr2;

The first is a primitive type int, the second is a constant pointer to an int, and I am trying to make a reference to the constant pointer in the second declaration with the third declaration. How can I go about doing this, if it is possible? The third declaration results in an error as it stands.

The current errors in Visual Studio 2015 express for Windows Desktop are the following:
1>------ Build started: Project: CppPractice, Configuration: Debug Win32 ------
1> CppPractice.cpp
1>c:\users\kevin\documents\visual studio 2015\projects\cpppractice\cpppractice\cpppractice.cpp(135): error C2373: 'ptr3': redefinition; different type modifiers
1> c:\users\kevin\documents\visual studio 2015\projects\cpppractice\cpppractice\cpppractice.cpp(130): note: see declaration of 'ptr3'
1>c:\users\kevin\documents\visual studio 2015\projects\cpppractice\cpppractice\cpppractice.cpp(156): warning C4227: anachronism used: qualifiers on reference are ignored
1>c:\users\kevin\documents\visual studio 2015\projects\cpppractice\cpppractice\cpppractice.cpp(156): error C2440: 'initializing': cannot convert from 'int *const ' to 'const int *&'
1> c:\users\kevin\documents\visual studio 2015\projects\cpppractice\cpppractice\cpppractice.cpp(156): note: Conversion loses qualifiers
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Last edited on
1
2
3
int x = 5;
int* const ptr2 = &x; // const pointer to (non-const) int
int* const& p_ref2 = ptr2; // lvalue reference to const pointer to (non-const) int 


When in doubt, or to make the code clearer, use type aliases. eg.
1
2
3
4
int x = 5;
using const_ptr_int = int* const ; // const pointer to (non-const) int
const_ptr_int ptr2 = &x;
const_ptr_int& p_ref2 = ptr2; // lvalue reference to const pointer to (non-const) int 
Last edited on
Topic archived. No new replies allowed.