可以将int **和const int **用作别名吗? [英] Is it okay for int** and const int** to alias?

查看:89
本文介绍了可以将int **和const int **用作别名吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,这样的事情还可以:

It is my understanding that something like this is okay:

const int ci = 42;
const int *cip = &ci;
int *ip = (int *)cip;
int j = *ip;

那呢?

const int ci = 42;
const int *cip = &ci;
const int **cipp = &cip;
int **ipp = (int **)cipp;
int j = **ipp;

推荐答案

表达式*ipp是类型为int *的左值,但是它被用于访问有效类型为const int *的对象. (即cip).

The expression *ipp is an lvalue of type int *, however it is being used to access an object of effective type const int *. (Namely, cip).

根据标准的字母,这是对别名的严格违反:允许的别名类型列表不包含别名T *的别名为const T *,反之亦然.

According to the letter of the standard, it is a strict aliasing violation: the list of allowed types to alias does not include aliasing T * as const T * or vice versa.

最接近的例外情况是:(C11 6.5/6摘录)

The closest exception is this one: (C11 6.5/6 excerpt)

  • 与对象的有效类型兼容的类型的合格版本
  • a qualified version of a type compatible with the effective type of the object

合格版本"由C11 6.2.5/26明确定义:

"qualified version" is clearly defined by C11 6.2.5/26:

每个不合格类型具有其类型的几个合格版本,分别与constvolatile,和restrict限定词.合格或不合格 类型的版本是属于同一类型类别的不同类型,并且具有相同的表示形式和对齐要求.派生类型不受派生类型的限定符(如果有)的限制.

Each unqualified type has several qualified versions of its type, corresponding to the combinations of one, two, or all three of the const, volatile, and restrict qualifiers. The qualified or unqualified versions of a type are distinct types that belong to the same type category and have the same representation and alignment requirements. A derived type is not qualified by the qualifiers (if any) of the type from which it is derived.

因此,例外情况是T可以别名为const T,反之亦然,但是指向可别名类型的指针没有类似的例外. const T *不是T *限定版本.

So the exception is that T may be aliased as const T and vice versa, but there is no similar exception for pointers to aliasable types. const T * is not a qualified version of T *.

但是当然有脚注:

此列表的目的是指定对象可能会别名也可能不会别名的那些情况

The intent of this list is to specify those circumstances in which an object may or may not be aliased

我不能说规则的意图是否使const T *T *具有别名.对我来说,不清楚T *const T *具有相同的表示和对齐要求"(6.2.5/28)的目的是什么,如果它不是别名的话.

I couldn't say whether the intent of the rule is for const T * and T * to be aliasable or not. It seems unclear to me what the purpose of specifying that T * and const T * have "the same representation and alignment requirements" (6.2.5/28) would be if it is not aliasable.

这篇关于可以将int **和const int **用作别名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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