gpt4 book ai didi

c++ - 从 char * * 变量分配给 char * const * 变量 - 为什么允许这样做?

转载 作者:行者123 更新时间:2023-11-30 01:12:58 25 4
gpt4 key购买 nike

令我惊讶的是 C++(Visual Studio 2012 编译器)的以下行为。

char * * PointerToPointerToChar = NULL;
char * const * PointerToConstPointerToChar = NULL;
char const * * PointerToPointerToConstChar = NULL;

PointerToPointerToConstChar = PointerToPointerToChar; // Assignment 1: Gives compiler error as I would expect
PointerToConstPointerToChar = PointerToPointerToChar; // Assignment 2: NO COMPILER ERROR ???

PointerToPointerToChar = PointerToPointerToConstChar; // Assignment 3: Gives compiler error as I would expect
PointerToPointerToChar = PointerToConstPointerToChar; // Assignment 4: Gives compiler error as I would expect

我了解 C++ 中的 const 关键字,特别是它的位置如何影响被视为 const 的内容(左侧的实体)。

编译器似乎试图保护 RHS 变量的用户免受 const-stripping 别名的影响在任一间接级别(赋值 3 和 4)。但是 LHS 仅在一个间接级别(赋值 1)而不是另一个间接级别(赋值 2)不受 const-stripping 别名的保护。换句话说,假设编译器阻止了以下内容

PointerToPointerToConstChar = PointerToPointerToChar; // Assignment 1: Gives compiler error as I would expect
PointerToPointerToChar[0][0] = 'A'; // The user of the LHS variable was effectively lied to about the constness of the *characters* - second level of indirection

那为什么编译器不阻止以下内容

PointerToConstPointerToChar = PointerToPointerToChar; // Assignment 2: NO COMPILER ERROR ???
PointerToPointerToChar[0] = NULL; // The user of the LHS variable was effectively lied to about the constness of the *pointers* - first level of indirection

这是正确的 C++ 吗?如果是,其基本原理是什么?似乎不一致。谢谢!

最佳答案

type const* 并不意味着该值不会改变,它意味着您不能使用该指针更改它。


因为如果你能做到这一点,你可以分配给 *PointerToPointerToConstChar 任何 const char* - 而 PointerToPointerToChar 依赖于它是正常的字符*。如果允许:

PointerToPointerToConstChar = PointerToPointerToChar; // assume PointerToPointerToChar is pointing to a valid memory block
const char str[] = "Hello world!";
*PointerToPointerToConstChar = str;
(*PointerToPointerToChar)[0] = 'X'; // Oops, we just modified a const array

关于c++ - 从 char * * 变量分配给 char * const * 变量 - 为什么允许这样做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33129931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com