本文介绍了可以将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)

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

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

因此,例外情况是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 *.

但是当然有脚注:

我不能说规则的意图是否使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 **用作别名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:39