I have the following C++ code snippet:
class T { };
void f(const T**) { }
int main() {
T *x = new T[5];
f(&x);
}
When I try to compile, g++ reports invalid conversion from 'T**' to 'const T**'. I have done some research and I understand this error. The typical fix is to change the definition of f(const T**) to f(const T* const*) which immediately fixes the problem.
Unfortunately, in my case, f is a function in another library and I cannot change the definition of f. How can I pass the address of x to f?
Instead you can pass the address of a pointer storing the same value as
x.When
freturns you can copy the value back intox.You can also cast the address. A write through
T const *to an object of typeT *is not an aliasing violation.The fact that this is valid is less obvious that simply passing a copy and then assigning back to
xin my opinion, anyway.