c ++中的malloc和构造函数 [英] malloc and constructors in c++

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

问题描述

是否可以使用 malloc 将参数传递给另一个类的构造函数中的某个类的构造函数?我可以使用 new 做到这一点。我需要对 malloc 做同样的事情:
(如果没有意义,请考虑我使用的是自定义分配器而不是malloc)

Is it possible to pass some parameters to constructor of a class inside a constructor of another class using malloc? I can do that with new. I need to do the same thing with malloc: (If it does not make sense, consider that I am using a custom allocator instead of malloc)

Class A_Class ... {
       public:
       B_Class *b;
...
     A_Class: ...
      { b = new B_Class (c1, c2, c3);
      } // end of constructor
}

现在带有malloc:

Now with malloc:

Class A_Class ... {
       public:
       B_Class *b;
...
     A_Class: ...
      { b = (B_Class*) malloc (sizeof(*b)); 
        ??????????????? }
}


推荐答案

malloc 分配原始内存。尝试将构造函数参数传递给它没有任何意义,因为它不会调用任何构造函数。

malloc allocates raw memory. There's no point in trying to pass constructor arguments to it because it doesn't call any constructors.

如果必须使用原始内存,则由您自己决定通过使用放置新语法

If you have to work with raw memory, it is up to you to construct an object in previously allocated raw memory by using "placement new" syntax

...
void *raw_b = malloc(sizeof *b);
b = new(raw_b) B_Class(c1, c2, c3); // <- placement new 
...

通常, b 将与 raw_b 相同,即无需额外的 raw_b 指针。但是我更喜欢用中间的 void * 指针来避免丑陋的转换。

Numerically, the value of b will be the same as raw_b, i.e. it is possible to get by without an extra raw_b pointer. But I prefer to do it this way, with an intermediate void * pointer, to avoid ugly casts.

当然,销毁此类物体时要小心。自定义分配需要自定义删除。一般情况下,您不能只是删除您的 b 。对称的自定义删除序列将涉及一个显式的析构函数调用,然后进行原始内存释放

Be careful when destroying such objects, of course. Custom allocation requires custom deletion. You can't just delete your b in general case. A symmetrical custom deletion sequence would involve an explicit destructor call followed by raw memory deallocation

b->~B_Class(); // <- explicit destructor call
free(b);

P.S。您可能会考虑采用另一种方法:在类中重载 operator new / operator delete ,而不是明确拼写自定义分配每次需要创建对象时。

P.S. You might consider going a different route: overloading operator new/operator delete in your class instead of spelling out custom allocation explicitly every time you need to create an object.

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

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