In critical embedded systems, dynamic memory allocation (malloc/new) is often banned to prevent heap fragmentation. However, we still want to use C++ objects with constructors. The solution is Placement New. This allows us to construct an object inside a pre-allocated "static" buffer (a simple byte array) rather than asking the OS for new memory.
Your task is to manually manage the lifecycle of a Driver object.
alignas(Driver) uint8_t buffer[...]).Driver object inside that buffer.ptr->~Driver()) when done, as delete cannot be used on static memory.Program Flow:
N.N times.cmd.cmd is "INIT": Read integer id. Construct a Driver with this ID inside the global driver_buffer using placement new.cmd is "USE": Call driver->operate().cmd is "DEINIT": Manually call the destructor.Input Format:
N (1 to 20).N lines: String cmd ("INIT", "USE", "DEINIT").Output Format:
Driver <id> Initializedoperate() prints: Driver <id> OperatingDriver <id> DestroyedExample:
Example 1
Input:
3
INIT 5
USE
DEINITOutput:
Driver 5 Initialized
Driver 5 Operating
Driver 5 DestroyedConstraints:
<new> header.new (address) Type(...).ptr->~Driver().new Driver(...) (standard heap allocation).
Input
3 INIT 5 USE DEINIT
Expected Output
Driver 5 Initialized Driver 5 Operating Driver 5 Destroyed