非类类型表达式的静态类型与动态类型之间的差异

Difference between static vs dynamic type for a non-class type expression

本文关键字:类型 之间 动态 静态 表达式 静态类      更新时间:2023-10-16

请考虑以下代码示例:

#include <cstdlib>
#include <iostream>
int main()
{
void *ptr  = malloc(sizeof(int));
char *cptr = reinterpret_cast<char*>(ptr);
*cptr;   // (0) What is the dynamic type here? Would sizeof(*cptr) return size of static or dynamic type and what would it be here?
int *iptr  = new (ptr) int{2};
*iptr;   // (1) Both static and dynamic type are int
cptr = reinterpret_cast<char*>(iptr);    
*cptr;   // (2) Is static type char and dynamic type int here?
}


到目前为止,我的理解是,由于继承进入图片,静态和动态类型通常因类类型而异。如果我对(2(的理解是正确的,那么对于非类类型,还有其他不同情况吗?

我问这个问题的原因是因为C++标准的以下定义:

[defns.dynamic.type]

派生最多的对象([intro.object](的类型,其中 由 glvalue 表达式表示的 glvalue 引用 [ 示例:如果 指针 ([dcl.ptr]( 静态类型为 "指针指向类 B" 的 P 为 指向类 D 的对象,派生自 B(子句 [class.derived](,表达式 *p 的动态类型是"D"。 参考文献([dcl.ref](的处理方式类似。 — 结束示例 ]

[defns.static.type]

表达式的类型 ([basic.types]( 由对 不考虑执行语义的程序 [ 注意:静态 表达式的类型仅取决于程序的形式,其中 表达式出现,并且在程序 执行。 — 尾注 ]

在上下文中,答案是否定的:C++动态类型取决于其动态调度机制,该机制仅在调用类的虚拟方法时使用。

请注意,在C++中,struct是声明类的另一种方式。