141. Static Driver Allocation

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.

  1. Create a raw byte buffer large enough to hold the object (alignas(Driver) uint8_t buffer[...]).
  2. Use Placement New to construct the Driver object inside that buffer.
  3. Use the object pointer to call methods.
  4. Crucially, you must manually call the Destructor (ptr->~Driver()) when done, as delete cannot be used on static memory.

Program Flow:

  1. Read integer N.
  2. Loop N times.
  3. Read string cmd.
  4. If cmd is "INIT": Read integer id. Construct a Driver with this ID inside the global driver_buffer using placement new.
  5. If cmd is "USE": Call driver->operate().
  6. If cmd is "DEINIT": Manually call the destructor.

Input Format:

  • First line: Integer N (1 to 20).
  • Next N lines: String cmd ("INIT", "USE", "DEINIT").
  • Input is provided via standard input (stdin).

Output Format:

  • Constructor prints: Driver <id> Initialized
  • operate() prints: Driver <id> Operating
  • Destructor prints: Driver <id> Destroyed

Example: 

Example 1

Input:

3
INIT 5
USE
DEINIT

Output:

Driver 5 Initialized
Driver 5 Operating
Driver 5 Destroyed

Constraints:

  • Must use <new> header.
  • Must use syntax: new (address) Type(...).
  • Must manually call ptr->~Driver().
  • Prohibited: new Driver(...) (standard heap allocation).

 

 

Loading...

Input

3 INIT 5 USE DEINIT

Expected Output

Driver 5 Initialized Driver 5 Operating Driver 5 Destroyed