42

我知道从右到左阅读声明的经验法则,我很确定我知道发生了什么,直到一位同事告诉我:

const MyStructure** ppMyStruct;

表示“ppMyStruct 是指向(可变) MyStructure 的 const 指针的指针”(在 C++ 中)。

我原以为这意味着“ppMyStruct 是指向 const MyStructure 的指针的指针”。我在 C++ 规范中寻找答案,但显然我不是很擅长...

in 在 C++ 中是什么意思,在 C 中是什么意思?

4

7 回答 7

66

你的同事错了。那是一个(非常量)指针,指向一个(非常量)指向 const MyStructure 的指针。在 C 和 C++ 中。

于 2008-12-03T09:30:48.433 回答
64

在这种情况下,工具 cdecl(或 c++decl)可能会有所帮助:

     [flolo@titan ~]$ cdecl explain "const struct s** ppMyStruct"
     declare ppMyStruct as pointer to pointer to const struct s
于 2008-12-03T09:44:52.353 回答
23

你的解释是对的。这是另一种看待它的方式:

const MyStructure *      *ppMyStruct;        // ptr --> ptr --> const MyStructure
      MyStructure *const *ppMyStruct;        // ptr --> const ptr --> MyStructure
      MyStructure *      *const ppMyStruct;  // const ptr --> ptr --> MyStructure

这些都是带有一个 const 限定符的指针的所有替代方案。从右到左的规则可用于破译声明(至少在 C++ 中;我不是 C 专家)。

于 2008-12-03T09:55:01.660 回答
7

你的同事错了,C和C++也是一样。尝试以下操作:

typedef struct foo_t {
    int i;
} foo_t;

int main()
{
    foo_t f = {123};
    const foo_t *p = &f;
    const foo_t **pp = &p;
    printf("f.i = %d\n", (*pp)->i);
    (*pp)->i = 888; // error
    p->i = 999;     // error
}

Visual C++ 2008 在最后两行给出以下错误:

error C2166: l-value specifies const object
error C2166: l-value specifies const object

GCC 4 说:

error: assignment of read-only location '**pp'
error: assignment of read-only location '*p'

G++ 4 说:

error: assignment of data-member 'foo_t::i' in read-only structure
error: assignment of data-member 'foo_t::i' in read-only structure
于 2008-12-03T09:45:45.067 回答
5

是对的。

另一个答案已经指向“顺时针螺旋规则”。我非常喜欢那个——不过有点精致。

于 2008-12-03T10:47:50.713 回答
3

作为其他评论的推论,不要把'const'放在第一位。它确实属于类型之后。那会立即阐明含义,只需照常阅读 RTL 即可:

MyStructure const** ppMyStruct;
于 2008-12-03T13:52:34.990 回答
0
void Foo( int       *       ptr,
          int const *       ptrToConst,
          int       * const constPtr,
          int const * const constPtrToConst )
{
    *ptr = 0; // OK: modifies the pointee
    ptr  = 0; // OK: modifies the pointer

    *ptrToConst = 0; // Error! Cannot modify the pointee
    ptrToConst  = 0; // OK: modifies the pointer

    *constPtr = 0; // OK: modifies the pointee
    constPtr  = 0; // Error! Cannot modify the pointer

    *constPtrToConst = 0; // Error! Cannot modify the pointee
    constPtrToConst  = 0; // Error! Cannot modify the pointer
}
于 2010-02-06T04:42:27.423 回答