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

时间:2010-07-01 20:04:13

标签: c++ malloc new-operator

  

可能重复:
  What is the difference between new/delete and malloc/free?
  In what cases do I use malloc vs new?

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

1 个答案:

答案 0 :(得分:4)

因为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!