【发布时间】:2020-09-28 22:00:13
【问题描述】:
考虑下面的代码示例:
#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++ standard 的以下定义:
[defns.dynamic.type]
类型的最派生对象([intro.object]) 由 glvalue 表达式表示的 glvalue 指的是 [ 示例:如果 静态类型为“指向 B 类的指针”的指针 ([dcl.ptr]) p 是 指向从 B 派生的 D 类对象(子句 [class.derived]),表达式 *p 的动态类型是“D”。 引用 ([dcl.ref]) 的处理方式类似。 —结束示例]
[defns.static.type]
表达式的类型 ([basic.types]) 从分析 程序不考虑执行语义[注:静态 表达式的类型仅取决于程序的形式 表达式出现,并且在程序运行时不会改变 执行。 ——尾注]
【问题讨论】:
-
(2)这里是静态类型char和动态类型int吗?是的。
-
还有其他与非类类型不同的情况吗?“任何其他情况”是什么意思?
-
@LanguageLawyer 如果在
malloc之后立即移动*cptr会怎样。那么动态类型是什么? -
@LanguageLawyer 我已经更新了代码 sn-p。检查
(0) -
你真的想要一个仅限于 C++11 的答案吗?
标签: c++ c++11 language-lawyer dynamictype