将 new 与使用 C malloc 的 C++ 构造函数一起使用
Using new with C++ Constructors that use C malloc
您能否在 C++ 的构造函数中安全地使用 malloc class 并使用 new 来创建该对象的实例?我知道在正常情况下将两者串联使用是不安全的,但在这种情况下是 possible/safe?
是的,你可以,但你应该有充分的理由。 new
运算符调用构造函数,它在许多方面就像常规 class
方法一样。您还应该将 free()
部分添加到析构函数中。
但请注意,如果您 malloc()
一个 c++ object the constructor of that object will not be called. I think there are very few reasons to call malloc()
in a c++ program: you probably wish to realloc()
later, which is one reason. But you can always use native c++ objects like stl 个容器。
在c++程序中使用这两种分配内存的方式并不是不安全的,你只需要注意不要malloc()
然后delete
它或 new
东西然后 free()
它。但是对于 malloc()
你总是必须小心很多事情,比如它返回 NULL
和 free()
ing 分配的内存所以它不是额外的东西。
再说一次,您可以做的最危险的事情是 malloc()
一个 c++ 对象。因为正如我已经说过的,构造函数不会被调用。
您能否在 C++ 的构造函数中安全地使用 malloc class 并使用 new 来创建该对象的实例?我知道在正常情况下将两者串联使用是不安全的,但在这种情况下是 possible/safe?
是的,你可以,但你应该有充分的理由。
new
运算符调用构造函数,它在许多方面就像常规class
方法一样。您还应该将free()
部分添加到析构函数中。但请注意,如果您
malloc()
一个 c++ object the constructor of that object will not be called. I think there are very few reasons to callmalloc()
in a c++ program: you probably wish torealloc()
later, which is one reason. But you can always use native c++ objects like stl 个容器。在c++程序中使用这两种分配内存的方式并不是不安全的,你只需要注意不要
malloc()
然后delete
它或new
东西然后free()
它。但是对于malloc()
你总是必须小心很多事情,比如它返回NULL
和free()
ing 分配的内存所以它不是额外的东西。再说一次,您可以做的最危险的事情是
malloc()
一个 c++ 对象。因为正如我已经说过的,构造函数不会被调用。