Is it safe to cast a function pointer accepting pointer type to another function pointer accepting reference type?

134 Views Asked by At

What are the drawbacks of casting a function pointer that accepts "Pointer parameter" to another function pointer that accepts "Reference parameter"?

consider the following example:

#include <iostream>
int test(int* x)
{
    (*x)*=2;
    return *x;
}

int main()
{
    int a = 5;
    int b = test(&a);
    std::cout<<"a="<<a<<" and b="<<b<<"\r\n";
    
    //Type casting:
    int (*test2)(int&) = (int(*)(int&))&test;
    
    int c = 5;
    int d = test2(c);
    std::cout<<"c="<<c<<" and d="<<d<<"\r\n";

    return 0;
}

It is useful specially when importing a function from a dynamic linked library (DLL). For example WriteFile function from Kernel32.dll has a syntax of:

BOOL WriteFile(
  HANDLE       hFile,
  LPCVOID      lpBuffer,
  DWORD        nNumberOfBytesToWrite,
  LPDWORD      lpNumberOfBytesWritten,
  LPOVERLAPPED lpOverlapped
);

which can be transferred to:

BOOL WriteFile(
  HANDLE       hFile,
  LPCVOID      lpBuffer,
  DWORD        nNumberOfBytesToWrite,
  DWORD&       NumberOfBytesWritten,
  OVERLAPPED&  Overlapped
);
1

There are 1 best solutions below

0
Adrian Mole On

Although reference and pointer arguments may (likely) be implemented with similar internal mechanics, a reference is not a pointer (see: What are the differences between a pointer variable and a reference variable?) and, as such, using one in lieu of the other is undefined behaviour.

Thus, a significant drawback of what you're doing in the shown code is that it produces undefined behaviour.

Any decent compiler would (or should) warn about this. Clang-cl (within Visual Studio) gives:

warning : cast from 'int (*)(int *)' to 'int (*)(int &)' converts to incompatible function type [-Wcast-function-type-strict]

And MSVC gives:

warning C4191: 'type cast': unsafe conversion from `'int (__cdecl *)(int *)' to 'int (__cdecl *)(int &)'
warning C4191: Making a function call using the resulting pointer may cause your program to fail