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

标签 c++

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 of the 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/

相关文章:

c++ - 容器类的成员不能是基类

C++11 多线程,通过引用传递

c++ - 如何分离调试和 Release模式代码

c++ - 有没有办法从构建脚本输出中解析依赖树?

c++ - 为 Visual Studio 2012 (ARPACK) 使用 dllwrap 生成 .dll 文件

c++ - 在我的 Windows 环境中使用的任何 tcl api (Tcl_*) 的段错误

c++ - 无法理解 C++ 中预递增/预递减的工作原理

C++,自动点击按钮

c++ - 使类模板成为其自身的 friend 以进行不同的实例化

c++堆删除任何元素的方法