Placement New Static Buffer

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

struct Block{
    int id; int value;
};

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

    //creating a buffer and aligning its memory address for Block onject

    alignas(Block) uint8_t buffer[sizeof(Block)];

    //place the struct object in the buffer and asign in to a str ptr

    Block *str_ptr = new (buffer) Block;

    str_ptr->id = id;
    str_ptr->value = value;

    cout << str_ptr->id << " " << str_ptr->value;

    str_ptr -> ~Block();

    return 0;
}

Solving Approach

 

 

 

 

 

 

Upvote
Downvote
Loading...

Input

7 42

Expected Output

7 42