60. unique_ptr Ownership Transfer

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

int main() {
    int N;
    cin >> N;

    // First and only owner initially
    unique_ptr<uint8_t[]> buf(new uint8_t[N]);

    for (int i = 0; i < N; i++) {
        int temp;
        cin >> temp;
        buf[i] = static_cast<uint8_t>(temp);
    }

    // Ownership is transferred explicitly
    unique_ptr<uint8_t[]> owner2 = std::move(buf);

    for (int i = 0; i < N; i++) {
        cout << static_cast<int>(owner2[i]);
        if (i != N - 1) cout << " ";
    }
    cout << endl;

    // After move, the original owner is empty
    if (buf == nullptr)
        cout << "No data" << endl;
    else
        cout << "Has data" << endl;

    return 0;
}

Explanation & Logic Summary:

std::unique_ptr enforces exclusive ownership by disabling copy construction and copy assignment. This guarantees that a dynamically allocated resource has exactly one owner at any point in time.

Ownership can only be transferred using std::move, which converts the source pointer into an rvalue and transfers responsibility to the destination std::unique_ptr. After the move, the original pointer becomes nullptr but remains valid.

This explicit ownership transfer prevents double-free errors and enforces correct lifetime management at compile time.

Firmware Relevance & Real-World Context:

In embedded and firmware systems, buffers, DMA regions, and hardware resources are often owned by a single subsystem at a time. Accidental duplication of ownership can lead to memory corruption, race conditions, or system crashes.

 

 

 

 

Loading...

Input

4 10 20 30 40

Expected Output

10 20 30 40 No data