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
);
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:
And MSVC gives: