简体   繁体   English

C ++内存分配器vptr /新实现

[英]c++ memory allocator vptr / new implementation

I was making a memory pool allocator for a project I am working on. 我正在为我正在处理的项目创建内存池分配器。 My pool allocator returns chunks of memory fine however my class inherits from another class. 我的池分配器返回的内存块很好,但是我的类继承自另一个类。

    MyClass *fx = (MyClass*)pool->allocateEffect(sizeof(MyClass));
    *fx = MyClass();

This doesn't setup the vtable for me. 这不会为我设置vtable。 I did some searching and found out the new operator can take in a chunk of memory. 我进行了一些搜索,发现新运算符可以占用大量内存。

    MyClass *fx = (MyClass*)pool->allocateEffect(sizeof(MyClass));
    fx = new(fx)MyClass();

And this will initialize the vptr. 这将初始化vptr。 So I was wondering if there is anyway to allocate the vptr my self or is it strictly up to the compilers whim? 所以我想知道是否有必要自行分配vptr还是严格取决于编译器的想法?

new(fx)MyClass()

This is called "placement new" and will actually call a constructor to actually create an object. 这称为“新放置”,实际上将调用构造函数来实际创建对象。

Until you created that object in the memory you allocated, it simply does not exist (as an object of that type) so it is just raw untyped memory that you cast to something, which results in undefined behavior. 在分配的内存中创建该对象之前, 它根本不存在 (作为该类型的对象),因此它只是原始的未类型化的内存,您将其强制转换为某种对象,从而导致未定义的行为。

I would suggest that you make your function a template like. 我建议您将函数设为类似模板。

template<class T>
T* allocateEffect() { return new (allocate_some_memory(sizeof(T))) T(); }

adding proper variadic templates and forwarding for constructor arguments is left as an exercise to the reader. 添加适当的可变参数模板并转发构造函数参数作为练习留给读者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM