jeudi 26 novembre 2020

combine allocation/construction Or deallocation/destruction with custom raw memory provision

I need to provide a utility function where both memory allocation and object construction take place and the user gets the pointer in return. Similarly, there is a need to provide a utility function for deallocation and destruction also.

Here is what I implemented: (I have not implemented for array type though)

#include <cstdlib> // for malloc
#include <iostream> // for cout
#include <string>  // for memset

// C++ class with some initial state x = 10
class SomeClass {
    public:
    SomeClass() : x(10) {}
    int x = 0;
};

template<typename T, typename ... Args>
inline T* MY_MODULE_NEW(Args&&... args) {
    // some custom allocator logic here which allocates just raw memory
    // for example purpose just use malloc
    void *p = malloc(sizeof(T));
    memset(p,0,sizeof(T));
    T* t = new(p) T(std::forward<Args>(args)...);
    return t;
}

template<typename T>
inline void MY_MODULE_DELETE(T* ptr) {
    ptr->~T();
    // some custom allocator logic here, which deallocates raw memory
    // for example purpose just use free
    free(ptr);
}

int main() {
    SomeClass* sc = MY_MODULE_NEW<SomeClass>();
    std::cout << sc->x << std::endl;

    SomeClass* sc2 = MY_MODULE_NEW<SomeClass>(*sc);
    std::cout << sc2->x << std::endl;

    MY_MODULE_DELETE(sc);
    MY_MODULE_DELETE(sc2);
}

I have the following concerns:

  1. From the performance point of view, Is this inline function good enough? Can we do better?
  2. Personally I feel MY_MODULE_NEW<SomeClass>(...) syntax is almost similar to the canonical syntax for operator new which is new SomeClass(). Is there any other idiomatic way to achieve the same result?

Thank You!

Aucun commentaire:

Enregistrer un commentaire