typedef 和 const 指针的容器

2022-01-24 00:00:00 containers c++ stl typedef

以下代码行编译得很好并且表现良好:

The following line of code compiles just fine and behaves:

list<const int *> int_pointers;  // (1)

以下两行没有:

typedef int * IntPtr;
list<const IntPtr> int_pointers;  // (2)

我得到完全相同的编译错误

I get the exact same compile errors for

list<int * const> int_pointers;  // (3)

我很清楚最后一行是不合法的,因为 STL 容器的元素需要是可分配的.为什么编译器将 (2) 解释为与 (3) 相同?

I'm well aware that the last line is not legal since the elements of an STL container need to be assignable. Why is the compiler interpreting (2) to be the same as (3) ?

推荐答案

简答:

  1. 是指向常量整数的指针列表.
  2. 是一个指向整数的常量指针列表.
  3. 与 2 相同.

const(和 volatile)自然应该出现在它们限定的类型之后.之前写的时候,编译器会在内部自动重写:

const (and volatile) should naturally appear after the type they qualify. When you write it before, the compiler automatically rewrites it internally:

const int *

变成

int const *

是一个指向常量 int 的指针.这些列表将编译得很好,因为指针本身仍然是可分配的.

which is a pointer to a constant int. Lists of these will compile fine since the pointer itself is still assignable.

相关文章