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

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

    The status quo is that malloc does not create objects. The only constructs that do are new expressions, definitions, casts and assignments to variant members. See P0137R0 for proper wording on this.

    If you wanted to use the storage yielded by malloc, assuming that it is properly aligned (which is the case unless you use extended alignments), employ a call to placement new:

    auto p = malloc(sizeof(int));
    int* i = new (p) int{0};
    // i points to an object of type int, initialized to zero
    

    Hence using malloc in C++ is quite useless, as bog-standard new effectively combines the above steps into one.

    See also @T.C.'s answer in the related question of the asker.

提交回复
热议问题