Static Driver Allocation

#include <iostream>
#include <new>      // Required for placement new
#include <cstdint>  // For uint8_t

class Driver {
    int id;
public:
    Driver(int i) : id(i) {
        std::cout << "Driver " << id << " Initialized" << std::endl;
    }
    ~Driver() {
        std::cout << "Driver " << id << " Destroyed" << std::endl;
    }
    void operate() {
        std::cout << "Driver " << id << " Operating" << std::endl;
    }
};

// Pre-allocated static memory block
// alignas ensures the processor can access the data correctly
alignas(Driver) uint8_t driver_buffer[sizeof(Driver)];

int main() {
    Driver* drv = nullptr; // Pointer to manage the object
    int N;
    if (!(std::cin >> N)) return 0;

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

        if (cmd == "INIT") {
            int id;
            std::cin >> id;
            // TODO: Use Placement New to construct Driver in 'driver_buffer'
            // Syntax: new (address) Type(arguments);
            drv = new(&driver_buffer) Driver(id);
        } else if (cmd == "USE") {
            if (drv) drv->operate();
        } else if (cmd == "DEINIT") {
            if (drv) {
                // TODO: Manually call the destructor
                drv->~Driver();
                
                // Reset pointer for safety
                drv = nullptr;
            }
        }
    }
    return 0;
}
Upvote
Downvote
Loading...

Input

3 INIT 5 USE DEINIT

Expected Output

Driver 5 Initialized Driver 5 Operating Driver 5 Destroyed