如何将“指针转换为指针类型"常量?

How to convert quot;pointer to pointer typequot; to const?(如何将“指针转换为指针类型常量?)
本文介绍了如何将“指针转换为指针类型"常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用下面的代码

void TestF(const double ** testv){;}
void callTest(){
    double** test;
    TestF(test);
}

我明白了:

'TestF' : cannot convert parameter 1 from 'double **' to 'const double **'

我不明白为什么.为什么 test 不能被无声地转换为 const double**?我为什么要明确地这样做?我知道

I cannot understand why. Why test cannot be silently casted to const double**? Why should I do it explicitly? I know that

TestF(const_cast<const double**>(test)) 

使我的代码正确,但我觉得这应该是不必要的.

makes my code correct, but I feel this should be unnecessary.

我缺少一些关于 const 的关键概念吗?

Are there some key concepts about const that I'm missing?

推荐答案

语言允许从 double **const double *const * 的隐式转换,但不能到const double **.您尝试的转换将隐含违反 const 正确性规则,即使它不是立即显而易见的.

The language allows implicit conversion from double ** to const double *const *, but not to const double **. The conversion you attempt would implicitly violate the rules of const correctness, even though it is not immediately obvious.

[de-facto standard] C++ FAQ 中的示例说明了这个问题

The example in the [de-facto standard] C++ FAQ illustrates the issue

https://isocpp.org/wiki/faq/const-correctness#constptrptr-conversion

基本上,规则是:在某个间接级别添加 const 后,您必须将 const 一直添加到所有间接级别.例如 int ***** 不能隐式转换为 int **const ***,但可以隐式转换为 int **const*const *const *

Basically, the rule is: once you add const at some level of indirection, you have to add const to all levels of indirection all the way to the right. For example, int ***** cannot be implicitly converted to int **const ***, but it can be implicitly converted to int **const *const *const *

这篇关于如何将“指针转换为指针类型"常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)