为什么下面给我一个转换错误从double ***为const双*** [英] Why does the following give me a conversion error from double *** to const double***

查看:193
本文介绍了为什么下面给我一个转换错误从double ***为const双***的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能将其转换双*** 常量双***

 无效美孚(const的双*** D)
{
}
INT主(整形变量,字符* []参数)
{
       双*** D;
       / *初始化D * /       餐饮);}


解决方案

如果你的C标记是可信的,GCC生成一个警告的类型为你的榜样和常量双* const的区别*常量* D 。在C ++中,它在OP code错误,但巴掌const的无处不在的做法是合法的。

,编译器会发出警告,其原因是,一个指针的指针(或进一步间接)允许一个指针通过修改位置的参数指向被返回给调用者。

如果指针的靶被声明为常量,则该调用的函数所期望它把有被视为上返回常量的值。

传递的一个更简单的情况下, T ** const的牛逼** 这说明了为什么这是一个错误是:

 无效美孚(为const char ** Z)
{
    * Z =A;
}
INT主(INT NARGS,焦炭** argv的)
{
    字符* Z = 0;
    焦炭** D =安培; Z;    //警告在C,错误C ++
    餐饮 );    //坏 - 修改常量数据
    Z [0] =Q;
}

常量在C表示,数据不会改变。 常量 C ++中意味着数据不会改变公开 - 在C ++对象可以改变的可变数据。 C编译器可以优化其code,使其缓存一些常量某处的数据,但C ++编译器不能这样做,因为可能mutablity,因此具有较弱的限制,你不能常量数据返回到非const如上。因此,在C ++中,双*** 可强制转换为常量双* const的* const的* D 作为额外的常量取值$ p的不可修改的内存$ pvent回报,但在C,如果编译器优化了重复访问内存其他地方产生一个警告和可能的错误。

Why can't it convert double *** to const double ***?

void foo(const double ***d)
{


}


int main (int args, char*[] args)
{
       double ***d;
       /*initialize d */

       foo(d);

}

解决方案

If your C tag is to be believed, gcc generates a warning as the types differ for both your example and const double * const * const * d. In C++, it's an error in the OP code but the slap-const-everywhere approach is legal.

The reason the compiler warns you is that a pointer to a pointer ( or further indirection ) allows a pointer to be returned to the caller by modifying the location the parameter points to.

If the target of the pointer is declared as const, then the called function would expect the value it puts there to be treated as const on return.

A simpler case of passing a T** to a const T** which illustrates why this is an error would be:

void foo ( const char ** z )
{
    *z = "A";
}


int main (int nargs, char** argv)
{
    char*   z = 0;
    char**  d = &z;

    // warning in C, error in C++
    foo ( d );

    // bad - modifies const data
    z[0] = 'Q';
}

const in C means that the data won't change. const in C++ means the data won't change publicly - mutable data in a C++ object can change. A C compiler could optimise its code so that it caches some of the const data somewhere, but a C++ compiler can't do that due to possible mutablity, so has the weaker restriction that you can't return const data to non-const as above. So in C++, double*** can be cast to const double * const * const * d as the extra consts prevent return of non-modifiable memory, but in C it generates a warning and possible errors if the compiler optimises repeated accesses to the memory elsewhere.

这篇关于为什么下面给我一个转换错误从double ***为const双***的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆