Why should I avoid using malloc in c++? [duplicate]

夙愿已清 提交于 2019-12-12 05:37:18

问题


Possible Duplicates:
What is the difference between new/delete and malloc/free?
In what cases do I use malloc vs new?

Why should I avoid using malloc in c++?


回答1:


Because malloc does not call the constructor of newly allocated objects.

Consider:

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!


来源:https://stackoverflow.com/questions/3161271/why-should-i-avoid-using-malloc-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!