0

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?

Community
  • 1
  • 1
Calvin
  • 2,872
  • 2
  • 21
  • 31

3 Answers3

4

Instead you can pass the address of a pointer storing the same value as x.

int main() {
    T *x = new T[5];
    T const *y = x;
    f(&y);
}

When f returns you can copy the value back into x.

You can also cast the address. A write through T const * to an object of type T * is not an aliasing violation.

int main() {
    T *x = new T[5];
    f(const_cast<T const**>(&x));
}

The fact that this is valid is less obvious that simply passing a copy and then assigning back to x in my opinion, anyway.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • Thanks for the prompt response! I'm glad there is a type-safe solution that doesn't involve const-cast. – Calvin Oct 06 '11 at 19:35
2
T const* x = new T[5];
f(&x);

or

T *x = new T[5];
f(&const_cast< T const*& >( x ) );
K-ballo
  • 80,396
  • 20
  • 159
  • 169
0
class T { };

void f(const T**) { }

int main() {
  T *x = new T[5];
  const T* y = x; // <====
  f(&y); // use y
}

http://ideone.com/oWZQR

Xeo
  • 129,499
  • 52
  • 291
  • 397