const 指针到指针在 C 和 C++ 中意味着什么?
我知道从右到左阅读声明的经验法则,并且我相当确定我知道发生了什么,直到一位同事告诉我:
const MyStructure** ppMyStruct;
意味着“ppMyStruct 是一个指向 const 指针的指针,该指针指向 (可变)MyStructure”(在 C++ 中)。
我本以为这意味着“ppMyStruct 是指向 const MyStructure 的指针”。 我在 C++ 规范中寻找答案,但显然我不太擅长...
in 在 C++ 中意味着什么,在 C 中意味着同样的事情吗?
I know the rule-of-thumb to read declarations right-to-left and I was fairly sure I knew what was going on until a colleague told me that:
const MyStructure** ppMyStruct;
means "ppMyStruct is a pointer to a const pointer to a (mutable) MyStructure" (in C++).
I would have thought it meant "ppMyStruct is a pointer to a pointer to a const MyStructure".
I looked for an answer in the C++ spec, but apparently I'm not very good at that...
What does in mean in C++, and does it mean the same thing in C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你是对的。
另一个答案已经指出了“顺时针螺旋法则"。 我非常喜欢那个——不过有点复杂。
You are right.
Another answer already pointed to the "Clockwise Spiral Rule". I liked that one very much - a little elaborate, though.
作为其他评论的推论,不要将“const”放在第一位。 它确实属于类型之后。 这会立即澄清其含义,只需像往常一样 RTL 阅读即可:
As a corollary to the other comments, don't put 'const' first. It really belongs after the type. That would have clarified the meaning immediately, just read it RTL as usual:
你的同事错了。 这是一个指向 const MyStructure 的(非常量)指针的(非常量)指针。 在 C 和 C++ 中。
Your colleague is wrong. That is a (non-const) pointer to a (non-const) pointer to a const MyStructure. In both C and C++.
在这种情况下,工具 cdecl(或 c++decl)可能会有所帮助:
In such cases the tool cdecl (or c++decl) can be helpfull:
你的解释是对的。 这是另一种看待它的方式:
这些都是带有一个 const 限定符的指针到指针的替代方案。 从右到左的规则可用于破译声明(至少在 C++ 中;我不是 C 专家)。
You were right in your interpretation. Here's another way to look at it:
These are all the alternatives of a pointer-to-pointer with one const qualifier. The right-to-left rule can be used to decipher the declarations (at least in C++; I'm no C expert).
你的同事错了,对于C和C++来说也是一样的。 请尝试以下操作:
Visual C++ 2008 在最后两行给出以下错误:
GCC 4 说:
G++ 4 说:
Your colleague is wrong, and it's the same for C and C++. Try the following:
Visual C++ 2008 gives the following errors for the last two lines:
GCC 4 says:
G++ 4 says: