141. Static Driver Allocation

#include <iostream>
#include <new>
#include <cstdint>

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;
    }
};

// Static buffer behaves like our "heap" but is fixed at compile time.
alignas(Driver) uint8_t driver_buffer[sizeof(Driver)];

int main() {
    Driver* drv = nullptr;
    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;
            // PLACEMENT NEW: Construct object at specific memory address
            // Does NOT allocate memory; just initializes it.
            drv = new (driver_buffer) Driver(id);
        } else if (cmd == "USE") {
            if (drv) drv->operate();
        } else if (cmd == "DEINIT") {
            if (drv) {
                // MANUAL DESTRUCTOR CALL: Required for placement new.
                // We cannot use 'delete drv' because memory is static.
                drv->~Driver();
                drv = nullptr;
            }
        }
    }
    return 0;
}

Explanation & Logic Summary:

  • The Buffer: uint8_t driver_buffer[sizeof(Driver)] reserves the exact number of bytes needed for one Driver object in the static memory area (BSS).
  • alignas(Driver): This tells the compiler to ensure the buffer starts at a memory address compatible with the Driver class (e.g., a multiple of 4 or 8 bytes). Without this, the CPU might crash (Bus Fault) when accessing the object.
  • new (ptr) Type: This is the syntax for placement new. It tells the constructor: "Don't find memory for me, use this pointer I gave you."
  • Destruction: Since delete ptr tries to free memory to the heap manager (which would crash here), we must call ptr->~Driver() explicitly to clean up the object's internal state.

Firmware Relevance & Real-World Context:

  • Shared Memory: If two CPU cores communicate via a specific RAM region (e.g., address 0x20008000), placement new is used to construct the shared object exactly at that address.
  • Determinism: This technique is standard in safety-critical C++ (like in ISO 26262 automotive code) because it allows using C++ objects without the non-deterministic timing risks of malloc/free.

 

 

 

Loading...

Input

3 INIT 5 USE DEINIT

Expected Output

Driver 5 Initialized Driver 5 Operating Driver 5 Destroyed