[英]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): 而错误是(VS 2008 Express):
error C2664: 'Test_myFunction.cpp' : cannot convert parameter 1 from 'float **' to 'const float **'
WTF? WTF? I'm casting a float** to const float**.
我正在将一个浮动**转换为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**?" 请阅读“为什么我在转换Foo **→Foo const **时出错?” at C++ FAQ.
在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. 虽然看起来很奇怪,它实际上可以减少某些模糊情况下的const正确性,允许您间接修改const对象。
See http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17 for the full details. 有关详细信息,请参阅http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17 。
What you can do is convert Foo**
to Foo const* const*
as that doesn't leave any back doors open. 你可以做的是将
Foo**
转换为Foo const* const*
,因为它不会让任何后门打开。
Just to add an important observation to the mostly valid answers: things are different for C and C++. 只是为大多数有效的答案添加一个重要的观察结果:C和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. 虽然这个技巧在C ++中使用
Foo const* const*
但这在C中不起作用,它不接受这个并发出警告。
In C you'd have to go more complicated ways if you want to have a typesafe cast to Foo const* const*
. 在C中,如果你想对
Foo const* const*
进行类型安全转换,你必须采用更复杂的方法。
float**
cannot be converted into const float**
. float**
无法转换为const float**
。
It can be converted into float* const*
and const float* const*
. 它可以转换为
float* const*
和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 与GCC编译: http : //ideone.com/RrIXl
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.