【问题标题】:How to convert "pointer to pointer type" to const?如何将“指向指针类型的指针”转换为 const?
【发布时间】:2013-11-23 11:41:57
【问题描述】:

用下面的代码

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

我明白了:

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

我不明白为什么。 为什么test 不能默默地转换为const double**? 我为什么要明确地这样做?我知道

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

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

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

【问题讨论】:

标签: c++ constants const-cast


【解决方案1】:

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

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

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

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

【讨论】:

  • “一直到右边”除了最后一个?
【解决方案2】:

double ** 不能隐式转换为const double ** 是正确的。不过,它可以转换为const double * const *

想象一下这个场景:

const double cd = 7.0;
double d = 4.0;
double *pd = &d;
double **ppd = &pd;
const double **ppCd = ppd;  //this is illegal, but if it were possible:
*ppCd = &cd;  //now *ppCd, which is also *ppd, which is pd, points to cd
*pd = 3.14; // pd now points to cd and thus modifies a const value!

因此,如果您的函数不打算修改任何涉及的指针,请将其更改为采用const double * const *。如果它打算做修改,你必须决定它所做的所有修改是否都是安全的,因此const_cast可以使用,或者你是否真的需要传入const double **

【讨论】:

    猜你喜欢
    • 2017-05-15
    • 2015-09-10
    • 2011-12-29
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多