What is the dynamic type of the object allocated by malloc?

后端 未结 5 2094
挽巷
挽巷 2021-01-12 09:31

The C++ standard refers to the term "dynamic type" (and the C standard refers to "effective type" in the similar context), for example

<
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-12 09:57

    As per 1.3.7 in C++11 standard,

    dynamic type glvalue type of the most derived object (1.8) to which the glvalue denoted by a glvalue expression refers [Example: if a pointer (8.3.1) p whose static type is “pointer to class B” is pointing to an object of class D, derived from B (Clause 10), the dynamic type of the expression *p is “D.” References (8.3.2) are treated similarly. — end example ]

    for an example

    class A {}
    class B : public A {}
    A *a = new B;
    

    the "static" type of a is A * while its dynamic type is B *.

    The idea of referencing not the same type comes to protect from something like

    class A{}
    class B : public A {int x;}
    class C : public A {int y;}
    A *a = new B;
    reinterpret_cast(a)->x;
    

    which may lead to undefined behavior.

    void * does not point to an object, but the distinction between dynamic and declaration type makes sense only for objects.

提交回复
热议问题