#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:
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."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:
0x20008000), placement new is used to construct the shared object exactly at that address.malloc/free.
Input
3 INIT 5 USE DEINIT
Expected Output
Driver 5 Initialized Driver 5 Operating Driver 5 Destroyed