【问题标题】:pointer and ampersand position with const in C++ [duplicate]C ++中带有const的指针和与号位置[重复]
【发布时间】:2024-01-14 18:44:01
【问题描述】:

可能重复:
Declaring pointers; asterisk on the left or right of the space between the type and name?

我一直想知道将*& 放在什么位置才是正确的。似乎 C++ 对放置这些标记的位置非常宽容。 例如,我似乎将指针和 & 号放在关键字的左右两侧或两个关键字的中间,但令人困惑的是,有时它们似乎意味着相同的东西,尤其是与 const 一起使用时@

void f1(structure_type const& parameter)
void f2(structure_type const &parameter)

void f2(structure_type  const *sptr);
void f2(structure_type  const* sptr);
void f2(structure_type  const * sptr);

示例并不详尽。在声明或传递给函数时,我到处都能看到它们。他们甚至是同一个意思吗?但我也看到在放置 * 时会影响哪个对象被称为指针的情况(可能是 * 位于两个关键字之间的情况)。

已编辑:

int const *Constant
int const * Constant // this above two seem the same to me, both as pointer to a constant value
int const* Constant //  EDIT: this one seems the same as above. instead of a constant pointer

const int * Constant // this is also a pointer to a constant value, but the word order changed while the pointer position stays the same, rather confusing.

int* const Constant
int * const Constant // instead, these two are constant pointers

所以我得出结论:

T const* p; // pointer to const T
const T* p  // seems same from above
T* const p; // const pointer to T

不过,这让我很困惑。编译器不关心它们所需的位置和间距吗?

编辑: 我想大致了解职位的重要性。如果是,在什么情况下。

【问题讨论】:

  • 这似乎意味着指针本身是常量 -- ideone.com/okePlO
  • 只是不要使用多个指针级别,否则你的头会爆炸:int const**const*const*const****const** wtf; Technically legal, but insane.
  • @chris this link 说它指向一个常量字段。但无论如何, const 的顺序可以改变的事实已经让我很困惑了。
  • @ryf9059, Read this。它工作得很好,但在这种情况下,从右到左阅读就足够了。

标签: c++ pointers constants


【解决方案1】:

空白仅在它阻止令牌一起运行和(例如)创建单个令牌的程度上很重要,因此(例如)int x 明显不同于intx

当您处理类似int const*x; 的内容时,* 的任一大小上的空格对编译器完全没有影响。

pointer to const intconst pointer to int 之间的区别取决于 const 在 * 的哪一侧。

int const *x;    // pointer to const int
int *const x;    // const pointer to int

主要区别在于当/如果您在同一声明中定义/声明多个对象时的可读性。

int* x, y;
int *x, y;

首先,有人可能认为 x 和 y 是指向 int 的指针——但实际上,x 是指向 int 的指针,而 y 是 int。在某些人看来,第二个更准确地反映了这一事实。

防止任何误解的一种方法是一次只定义一个对象:

int *x;
int y;

对于其中任何一个,如果您完全忽略空格(除了告诉您一个令牌在哪里结束而另一个开始,所以您知道“const int”是两个令牌)并从右到左阅读,正确的解释是相当容易的,阅读* 作为“指针”。例如:int volatile * const x; 读作“x 是指向 volatile int 的 const 指针”。

【讨论】:

  • 与正在解释的理论无关的吹毛求疵:需要初始化一个常量指针。 int *const x; 将导致编译错误,这是正确的。
【解决方案2】:
int const *Constant
int const * Constant 
int const* Constant

以上所有内容都打算声明一个指向常量整数的非常量指针。

简单规则:

如果const 跟在* 之后,则它适用于指针,否则它适用于指向的对象。间距无关紧要。

【讨论】:

    【解决方案3】:

    变量声明中的 & 和 * 放置都是可以接受的,仅取决于您自己的风格。它们严格意义上的意思是一样的,分别创建一个指针和一个引用。

    然而,const 关键字的位置是原始的,因为 int const* variable 声明了一个 constant 指向 非常量 int 的指针,而 const int* variable 是一个 非常量指向常量 int的指针。

    【讨论】:

    • int const * variable 定义了一个指向 const int 的指针,而指针本身仍可能发生变异。
    • 事实上,你的答案中的两个表示是同一个意思。