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

后端 未结 5 1991
挽巷
挽巷 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:56

    Dynamic type is a formal term to describe essentially polymorphic objects i.e. ones with at least one virtual function. It is thus a C++ term as C has no concept of virtual, for example.

    But how is the dynamic type of the object allocated with malloc determined?

    It isn't. malloc allocates N raw bytes of memory and returns it through a void* - it's your job to infer the right type. Moreover, this memory just represents the area where the object is placed, but this object will not be alive till you explicitly call its constructor. (again, from a C++ perspective)

    Will the dynamic type of the object pointed to by pi be int?

    No, because the term dynamic type is meaningful when describing object with class types. int is not nor can be.

    class Foo
    {
       //virtual ~Foo() = default; 
       virtual void f() {}
    };
    
    class Bar : public Foo
    {
      virtual void f() {}
    };
    
    // ...
    Foo *ptr = new Bar();
    

    Here Foo is the static type of ptr while Bar is its dynamic type.

提交回复
热议问题