Static Object Pool

#include <iostream>
#include <string>

struct Message {
    int id;
};

class MessagePool {
private:
    static Message pool[3];
    static bool in_use[3];

public:
    // TODO: Implement allocate()
    // Find first false in 'in_use', mark true, return pointer to pool[i]
    static Message* allocate() {
        // Return nullptr if full
        int i=-1;
        for (int j=0; j<3; j++) {
            if (in_use[j]==false) {
                i=j;
                in_use[j] = true;
                break;
            }
        }
        if (i==-1) return nullptr; // Placeholder
        return &pool[i];
    }

    // TODO: Implement release(Message* m)
    // Mark the corresponding slot as false
    static void release(Message* m) {
        // Calculate index: i = m - pool
        // in_use[i] = false;
        int i = getIndex(m);
        in_use[i]=false;
    }

    // Helper to get pointer by index (for main loop usage only)
    static Message* getSlot(int index) {
        if (index >= 0 && index < 3) return &pool[index];
        return nullptr;
    }
    
    // Helper to get index by pointer
    static int getIndex(Message* m) {
        return m - pool;
    }
};

// TODO: Define static members
Message MessagePool::pool[3];
// bool MessagePool::in_use[3]; // Missing definition will cause link error
bool MessagePool::in_use[3];

int main() {
    // Define in_use here just to make template compile for now
    // (Student should define it properly above)
    // bool dummy[3] = {false}; 
    bool dummy[3] = {false};
    int N;
    if (!(std::cin >> N)) return 0;

    for (int i = 0; i < N; ++i) {
        std::string cmd;
        std::cin >> cmd;

        if (cmd == "ALLOC") {
            int id;
            std::cin >> id;
            Message* m = MessagePool::allocate();
            if (m) {
                m->id = id;
                std::cout << "Allocated Slot " << MessagePool::getIndex(m) << std::endl;
            } else {
                std::cout << "Pool Full" << std::endl;
            }
        } else if (cmd == "FREE") {
            int idx;
            std::cin >> idx;
            Message* m = MessagePool::getSlot(idx);
            if (m) {
                MessagePool::release(m);
                std::cout << "Freed Slot " << idx << std::endl;
            }
        }
    }
    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

5 ALLOC 100 ALLOC 200 ALLOC 300 ALLOC 400 FREE 1

Expected Output

Allocated Slot 0 Allocated Slot 1 Allocated Slot 2 Pool Full Freed Slot 1