25. Placement New Static Buffer

#include <iostream>
#include <cstdint>
#include <new>
using namespace std;

// Simple struct representing a data block
struct Block {
    int id;
    int value;
};

int main() {
    int id, value;
    cin >> id >> value;

    // Properly aligned static buffer for one Block
    alignas(Block) uint8_t buffer[sizeof(Block)];

    // Construct Block object inside buffer using placement new
    Block* ptr = new (buffer) Block;

    ptr->id = id;
    ptr->value = value;

    // Output fields
    cout << ptr->id << " " << ptr->value;

    // Explicit destructor call (required for placement new)
    ptr->~Block();

    return 0;
}

Explanation & Logic Summary:

  • alignas(Block) guarantees correct alignment for the object
  • uint8_t buffer[sizeof(Block)] reserves raw memory only
  • new (buffer) Block constructs the object in-place
  • Placement new does not allocate memory
  • Destructor must be called manually
  • This pattern avoids heap usage entirely

Firmware Relevance & Real-World Context:

  • Placement new is widely used when:
    • Heap allocation is forbidden
    • Objects must live in static memory
    • Drivers, RTOS objects, or protocol stacks are constructed in-place
  • Proper alignment is mandatory on many MCUs
  • This pattern is common in safety-critical and real-time firmware systems

 

 

 

 

 

Loading...

Input

7 42

Expected Output

7 42