Placement New Static Buffer

#include <iostream>
#include <new>      // placement new
#include <cstddef>  // std::aligned_storage

using namespace std;

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

int main() {
    // Create statically allocated, properly aligned buffer
    alignas(Block) unsigned char buffer[sizeof(Block)];

    // Construct Block object in the buffer using placement new
    Block* blk = new (buffer) Block;

    // Read input values
    cin >> blk->id >> blk->value;

    // Print the fields
    cout << blk->id << " " << blk->value;

    // Manually call destructor
    blk->~Block();

    return 0;
}

Solving Approach

 

 

 

 

 

 

Upvote
Downvote
Loading...

Input

7 42

Expected Output

7 42