dimanche 12 juillet 2020

Threadsafe delete in C++

My question is not how to make this feature from scratch, but whether my implementation can be used.

I have the next classes:

    class PointerStorage
    {
    private:
        static std::mutex m;
        static std::unordered_set<void*> pointers;
    public:
        static inline void add(void* ptr){
            m.lock();
            PointerStorage::pointers.insert(ptr);
            m.unlock();
        }
        static inline bool tryRemove(void* ptr) {
            std::lock_guard<std::mutex> g(m);
            return PointerStorage::pointers.erase(ptr);
        }
        static inline bool hasPtr(void* ptr) {
            std::lock_guard<std::mutex> g(m);
            return PointerStorage::pointers.find(ptr) != PointerStorage::pointers.end();
        }
    };
    class Deletable
    {
    public:
        void* operator new(size_t size) {
            void* p = malloc(size);
            PointerStorage::add(p);
            return p;
        }
        void operator delete(void* ptr) {
            if (PointerStorage::tryRemove(ptr)) {
                free(ptr);
            }
        }
    };

My idea is to inherit from Deletable if necessary and use the operators

But I'm wondering if such a situation is possible:

  • I create an object in variable OBJ, delete it.
  • I create a new object in another variable, its address becomes the same as it was in OBJ and the delete operation on OBJ affects my new object.

Aucun commentaire:

Enregistrer un commentaire