Placement New Static Buffer

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

// Define struct Block
struct Block {
    int id;
    int value;

    // Constructor
    Block(int i, int v) : id(i), value(v) {}

    // Destructor
    ~Block() {}
};

// Create statically allocated, properly aligned buffer
alignas(Block) static uint8_t buffer[sizeof(Block)];

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

    // Construct Block object inside buffer using placement new
    Block* obj = new (buffer) Block(id, value);

    // Print fields
    cout << obj->id << " " << obj->value;

    // Explicitly call destructor
    obj->~Block();

    return 0;
}

Solving Approach

 

 

 

 

 

 

Upvote
Downvote
Loading...

Input

7 42

Expected Output

7 42