How to fix this C++ Memory Management?

Viewed 69

I want to build a Memory Management to avoid memory leak but my code has an error that I have no idea how to fix, and how to fix the error in the code?

There: EMC_DELETE cls2; // <-- error: expected a ';'

This code is referenced from a GLSL parser (https://github.com/graphitemaster/glsl-parser/blob/main/ast.h).

// A helper function to help other to reproduce the same example.
std::string pathFolderOrFileName(const std::string &path) {
    return path.substr(path.find_last_of("/\\") + 1);
}

template <typename T>
static inline void _destroy(void *self) {
    ((T*)self)->~T();
    free(self);
}
struct Memory {
    // Memory Management that's referenced from "emc-language > lexer-parser > ast.h".
    Memory() : data(0), dtor(0) { }
    template <typename T>
    Memory(T *data, const char *file, int line) :
        data((void*)data),
        dtor(&_destroy<T>),
        file(file),
        line(line)
    {}
    
    void *data;
    void (*dtor)(void*);
    const char *file;
    int line;
    
    void destroy() {
        dtor(data);
    }
};

template <typename T>
struct Node {
    void *operator new(size_t size, std::vector<Memory> *collector, const char *file, int line) throw() {
        void *data = malloc(size);
        if (data) {
            collector->push_back(Memory((T *)data, file, line));
        }
        return data;
    }

    void operator delete(void *data, std::vector<Memory> *collector) {
        auto &vec = *collector;
        for (int i = 0; i < vec.size(); i++) {
            if (vec[i].data == data) {
                vec.erase(vec.begin() + i);
                free(data);
                return;
            }
        }
        assert(0);
    }
};

// Note: Never use the default 'operator new & delete' because they can cause memory leak.
#define EMC_NEW new(&g_memory, __FILE__, __LINE__) // Use this instead of using the default 'operator new'.
#define EMC_DELETE delete(&g_memory)               // Use this instead of using default 'operator delete'.

//----------------------------------------------------------------------------------------------------

class MyBaseClass {
public:
    int base_x, base_y;
};

class MyClass : public Node<MyClass> {
public:
    int x, y;

    MyClass() {
    }
    ~MyClass() {
    }
};

std::vector<Memory> g_memory;

int main() {
    MyClass *cls0 = EMC_NEW MyClass();
    MyClass *cls1 = EMC_NEW MyClass();
    MyClass *cls2 = EMC_NEW MyClass();
    EMC_DELETE cls2; // <-- error: expected a ';'

    for (int i = 0; i < g_memory.size(); i++) {
        auto &it = g_memory[i];
        printf("%d: (file \"%s\", line %d)\n", i, pathFolderOrFileName(it.file).c_str(), it.line);
    }

    return 0;
}

Expected output:

0: (file "test_draft.cpp", line 79)
1: (file "test_draft.cpp", line 80)
2: (file "test_draft.cpp", line 81) this line must be removed because cls2 must be deleted.
0 Answers
Related