为什么我应该避免在c ++中使用malloc? [英] Why should I avoid using malloc in c++?

查看:194
本文介绍了为什么我应该避免在c ++中使用malloc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复项:

new / delete和malloc / free之间有什么区别?

在什么情况下使用malloc vs new?

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

Why should I avoid using malloc in c++?

推荐答案

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

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

请考虑:

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!

这篇关于为什么我应该避免在c ++中使用malloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆