gpt4 book ai didi

c++ - 通过引用访问是否违反了严格的别名规则?

转载 作者:搜寻专家 更新时间:2023-10-30 23:55:04 24 4
gpt4 key购买 nike

我知道 int* ptr = (int*)buffer(其中 bufferchar*)中断严格别名规则。

这个语法 int& ref = (int&)(*buffer) 是否也违反了规则?

had一些由于违反严格的别名规则而导致的 SEGFAULT,此语法已将其消除。虽然可能仍然不正确,是吗?

最佳答案

这不行(假设您要使用所述引用来访问该值)。 § 3.10 [basic.lval] ¶ C++14 标准的第 10 条(引用 N4140)说(强调我的):

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:

  • the dynamic type of the object,
  • a cv-qualified version of the dynamic type of the object,
  • a type similar (as defined in 4.4) to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
  • 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),
  • a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
  • a char or unsigned char type.

尝试通过指针还是引用访问并不重要。对于 char 类型的存储对象,没有任何要点适用于允许将其作为 int 进行访问。

最后一个要点仅表示您可以将任何 other 类型别名为 char,但反之则不行。这是有道理的,因为 char 是具有最弱对齐要求的最小可寻址单元。

如果您愿意,使用指针与使用引用是一样的,只是您需要显式取消引用才能访问该值。

关于c++ - 通过引用访问是否违反了严格的别名规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33849613/

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