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

Solving Approach

 

 

 

 

 

 

Upvote
Downvote
Loading...

Input

7 42

Expected Output

7 42