Passing by reference of a pointer to a const object

  c++, constants, double-pointer, pointers, reference

I’ve been working on a project that using good amount of double pointers and I was finding I was getting some bugs with it. After spending some time digging into it I’ve realised the issue is when you pass a non-const object via a reference of a pointer to a const object it ends up getting passed by copy instead of reference. I don’t understand why this would be the case, since a reference is just an alias and the const part should just cause an error if you try to change something about the object in that scope. To further this confusion this does not happen when passing by a double-pointer of a const object or when it’s just a reference to a const object. Can anyone explain why this is happening and how this particular case is different from the others I’ve included?

#include <iostream>

void PassByConstPtrRef(int const *const &num_ptr_ref)
{
    std::cout << &num_ptr_ref << std::endl;
}

void PassByPtrRef(int *const &num_ptr_ref)
{
    std::cout << &num_ptr_ref << std::endl;
}

void PassByPtrPtr(int const *const *const num_ptr_ref)
{
    std::cout << num_ptr_ref << std::endl;
}

void PassByConstRef(int const &num)
{
    std::cout << &num << std::endl;
}

int main()
{
    int *num_ptr = new int{ 10 };
    int *const *num_ptr_ptr = &num_ptr;
    int *const &num_ptr_ref = *num_ptr_ptr;

    std::cout << num_ptr_ptr << " : " << &num_ptr_ref << std::endl; // is equal

    std::cout << num_ptr_ptr << " : ";
    PassByConstPtrRef(num_ptr_ref); // is not equal

    std::cout << num_ptr_ptr << " : ";
    PassByPtrRef(num_ptr_ref); // is equal

    std::cout << num_ptr_ptr << " : ";
    PassByPtrPtr(&num_ptr_ref); // is equal

    int foo = 4;
    int &bar = foo;

    std::cout << &foo << " : ";
    PassByConstRef(bar); // is equal
}

Source: Windows Questions C++

LEAVE A COMMENT