Malloc和构造函数 [英] Malloc and constructors

查看:708
本文介绍了Malloc和构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与新的和删除操作符不同,malloc在创建对象时不会调用构造函数。在这种情况下,我们必须创建一个对象,以便调用构造函数。

Unlike new and delete operators malloc does not call the constructor when an object is created. In that case how must we create an object so that the constructor will also be called.

推荐答案

c $ c> new ?这是点子。

Er...use new? That's kind of the point. You can also call the constructor explicitly, but there's little reason to do it that way

A* a = new A();

delete a;



显式调用构造函数/析构函数(\"placement new):



Calling the constructor/destructor explicitly ("placement new"):

A* a = (A*)malloc(sizeof(A));
new (a) A();

a->~A();
free(a);

这篇关于Malloc和构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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