Reinitialize Object In-Place

#include <iostream>
#include <cstdint>
#include <new> // Required for placement new

using namespace std;

// Define the struct
struct Mode {
    int level;

    // Constructor to initialize level
    Mode(int l) : level(l) {}

    // Destructor (manual call required for placement new)
    ~Mode() {
        // In a real system, you might release hardware resources here
    }
};

int main() {
    int firstLevel, secondLevel;
    if (!(cin >> firstLevel >> secondLevel)) return 0;

    // 1. Create a statically allocated, properly aligned buffer
    alignas(Mode) uint8_t buffer[sizeof(Mode)];

    // 2. Construct the first object in the buffer
    Mode* modePtr = new (buffer) Mode(firstLevel);

    // 3. Manually call the destructor
    modePtr->~Mode();

    // 4. Reconstruct the second object in the same buffer
    modePtr = new (buffer) Mode(secondLevel);

    // 5. Print the final level
    cout << modePtr->level << endl;

    // 6. Clean up the final object
    modePtr->~Mode();

    return 0;
}

Solving Approach

 

 

 

 

 

 

Upvote
Downvote
Loading...

Input

3 9

Expected Output

9