为什么我应该避免在c ++中使用malloc?

可能重复:
new / delete和malloc / free有什么区别?
我在哪些情况下使用malloc vs new?

为什么我应该避免在c ++中使用malloc


因为malloc不调用新分配的对象的构造函数。

考虑:

class Foo
{
public:
    Foo() { /* some non-trivial construction process */ }
    void Bar() { /* does something on Foo's instance variables */ }
};

// Creates an array big enough to hold 42 Foo instances, then calls the
// constructor on each.
Foo* foo = new Foo[42];
foo[0].Bar(); // This will work.

// Creates an array big enough to hold 42 Foo instances, but does not call
// the constructor for each instance.
Foo* foo = (Foo*)malloc(42 * sizeof(Foo));
foo[0].Bar(); // This will not work!
链接地址: http://www.djcxy.com/p/13773.html

上一篇: Why should I avoid using malloc in c++?

下一篇: Differences between `malloc` and `new`