why no implicit conversion from pointer to reference to const pointer.

Posted by user316606 on Stack Overflow See other posts from Stack Overflow or by user316606
Published on 2010-05-25T20:24:15Z Indexed on 2010/05/25 20:31 UTC
Read the original article Hit count: 167

Filed under:
|
|

I'll illustrate my question with code:

#include <iostream>

void PrintInt(const unsigned char*& ptr)
{
    int data = 0;
    ::memcpy(&data, ptr, sizeof(data));
    // advance the pointer reference.
    ptr += sizeof(data);
    std::cout << std::hex << data << " " << std::endl;
}

int main(int, char**)
{
    unsigned char buffer[] = { 0x11, 0x11, 0x11, 0x11, 0x22, 0x22, 0x22, 0x22, };

    /* const */ unsigned char* ptr = buffer;

    PrintInt(ptr);  // error C2664: ...
    PrintInt(ptr);  // error C2664: ...    

    return 0;
}

When I run this code (in VS2008) I get this: error C2664: 'PrintInt' : cannot convert parameter 1 from 'unsigned char *' to 'const unsigned char *&'. If I uncomment the "const" comment it works fine.

However shouldn't pointer implicitly convert into const pointer and then reference be taken? Am I wrong in expecting this to work? Thanks!

© Stack Overflow or respective owner

Related posts about c++

Related posts about pointers