gpt4 book ai didi

c++ - 通过指向其派生类的指针访问类对象是否会违反严格的别名规则?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:16 24 4
gpt4 key购买 nike

void foobar(Base* base)
{
Derived* derived = dynamic_cast<Derived*>(base); // or static_cast
derived->blabla = 0xC0FFEE;
if (base->blabla == 0xC0FFEE)
...
}

在具有严格别名 的编译器上,“derived”是“base”的别名吗?

最佳答案

只要有可能通过它们访问同一个对象,两个指针就被别名化了。该标准的第 3.10/15 段指定了对对象的访问何时有效。

If a program attempts to access the stored value of an object through an lvalue 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 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 ofthe object,
  • an aggregate or union type that includes one of the aforementioned types among its members (including,recursively, a 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.

在您的情况下,*derived 要么是对象动态类型的左值,要么是对象动态类型的基类类型。 *base 是对象动态类型的基类类型。

因此,您可以通过derivedbase 访问对象,使这两个指针成为别名。

关于c++ - 通过指向其派生类的指针访问类对象是否会违反严格的别名规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1546997/

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