将 new 与使用 C malloc 的 C++ 构造函数一起使用

Using new with C++ Constructors that use C malloc

您能否在 C++ 的构造函数中安全地使用 malloc class 并使用 new 来创建该对象的实例?我知道在正常情况下将两者串联使用是不安全的,但在这种情况下是 possible/safe?

  1. 是的,你可以,但你应该有充分的理由。 new 运算符调用构造函数,它在许多方面就像常规 class 方法一样。您还应该将 free() 部分添加到析构函数中。

    但请注意,如果您 malloc() 一个 object the constructor of that object will not be called. I think there are very few reasons to call malloc() in a program: you probably wish to realloc() later, which is one reason. But you can always use native objects like 个容器。

  2. 程序中使用这两种分配内存的方式并不是不安全的,你只需要注意不要malloc()然后delete 它或 new 东西然后 free() 它。但是对于 malloc() 你总是必须小心很多事情,比如它返回 NULLfree()ing 分配的内存所以它不是额外的东西。

    再说一次,您可以做的最危险的事情是 malloc() 一个 对象。因为正如我已经说过的,构造函数不会被调用。