开发者

C/C++ Cast to const weirdness

I have a function declared as:

int m开发者_StackOverflow社区yFunction(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!!! :)


Please read "Why am I getting an error converting a Foo** → Foo const**?" at C++ FAQ.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜