简体   繁体   中英

C/C++ Cast to const weirdness

I have a function declared as:

int myFunction(const float** ppArr, const int n, const int m);

and when I call it like so:

float** ppArr = new float*[5];
// Some initialization of ppArr

int result = myFunction(ppArr, 5, 128);  <<<< Error

and the error is (VS 2008 Express):

error C2664: 'Test_myFunction.cpp' : cannot convert parameter 1 from 'float **' to 'const float **'

WTF? I'm casting a float** to const float**. What could possibly go wrong with that ? :/

Edit: Thank you for incredibly fast responses!!! :)

As strange as it seems, it could actually reduce const-correctness in certain obscure cases, allowing you to modify a const object indirectly.

See http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17 for the full details.

What you can do is convert Foo** to Foo const* const* as that doesn't leave any back doors open.

Just to add an important observation to the mostly valid answers: things are different for C and C++. Whereas the trick works in C++ with Foo const* const* this doesn't work in C, it wouldn't accept this and throw a warning.

In C you'd have to go more complicated ways if you want to have a typesafe cast to Foo const* const* .

float** cannot be converted into const float** .

It can be converted into float* const* and const float* const* . Like this:

void f(float* const* p) {}

void h(const float* const* p) {}

int main() {
    float** p= new float*[5];
    f(p);
    h(p);
}

Compile it with GCC: http://ideone.com/RrIXl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM