gpt4 book ai didi

c++ - 将结构别名为其第一个成员是否是严格的别名违规?

转载 作者:IT老高 更新时间:2023-10-28 21:42:04 37 4
gpt4 key购买 nike

示例代码:

struct S { int x; };

int func()
{
S s{2};
return (int &)s; // Equivalent to *reinterpret_cast<int *>(&s)
}

我认为这是常见的,并且被认为是可以接受的。该标准确实保证结构中没有初始填充。但是这种情况并没有在严格的别名规则(C++17 [basic.lval]/11)中列出:

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

  • (11.1) the dynamic type of the object,
  • (11.2) a cv-qualified version of the dynamic type of the object,
  • (11.3) a type similar (as defined in 7.5) to the dynamic type of the object,
  • (11.4) a type that is the signed or unsigned type corresponding to the dynamic type of the object,
  • (11.5) a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
  • (11.6) an aggregate or union type that includes one of the aforementioned types among its elements or non-static data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
  • (11.7) a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
  • (11.8) a char, unsigned char, or std::byte type.

似乎很明显,对象 s 正在访问其存储的值。

项目符号中列出的类型是进行访问的泛左值的类型,而不是被访问对象的类型。在这段代码中,glvalue 类型是 int,它不是聚合或 union 类型,排除了 11.6。

我的问题是:这段代码是否正确,如果正确,在上述哪个要点下是允许的?

最佳答案

Actor 的行为归结为 [expr.static.cast]/13;

A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T , then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.

pointer-interconvertible的定义是:

Two objects a and b are pointer-interconvertible if:

  • they are the same object, or
  • one is a union object and the other is a non-static data member of that object, or
  • one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, the first base class subobject of that object, or
  • there exists an object c such that a and c are pointer-interconvertible, and c and b are pointer-interconvertible.

所以在原始代码中,ss.xpointer-interconvertible 并且遵循 (int &)s 实际上指定 s.x

所以,在严格的别名规则中,存储值被访问的对象是s.x而不是s,所以没有问题,代码是正确的。

关于c++ - 将结构别名为其第一个成员是否是严格的别名违规?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50383187/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com