转化会失去限定符,但实际上并非如此

Conversion loses qualifiers, but doesn't really

本文关键字:实际上 并非如此 失去      更新时间:2023-10-16

这有点类似,但也有点不同:c++ "转换失去限定符"编译错误

在我的代码,我得到以下错误:

错误C2440:"初始化":无法从"const git_commit"转换*const *' to 'const git_commit **'

正如我所理解的,从T**赋值到const T**将允许违反constness规则,在我给出的例子中,也就是说,从const T*const *赋值到const T**实际上获得了constness,而没有失去任何,那么这在哪里/为什么是一个问题?

const git_commit * const *

指向指向常量git_commits的指针数组

const git_commit * *

指向指向常量git_commits的可变数组的指针

将const数组赋值给可变数组会丢失const。

int const x = 7;
std::cout << x << 'n'; // compiler can optimize to 7
int const* const px = &x;
std::cout << *px << 'n'; // compiler can optimize to 7
int const*const* ppx = &px;
std::cout << **ppx << 'n'; // compiler can optimize to 7
int const** ppx_cheat = ppx; // illegal, but presume we are allowed to do it
int const y = 1;
int const* py = &y;
*ppx_cheat = py;
std::cout << **ppx << 'n'; // compiler can optimize to 7, *but is wrong*