typedef 和 const 指针的容器 [英] typedef and containers of const pointers

查看:33
本文介绍了typedef 和 const 指针的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于typedef 和 const 指针的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆