unique_ptr Ownership Transfer

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

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

    // buf owns the buffer
    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);
    }

    // Invalid: attempts to create a second owner
    unique_ptr<uint8_t[]> owner2;
    owner2 = std::move(buf);

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

    if (buf == nullptr)
        cout << "No data" << endl;
    else
        cout << "Has data" << endl;

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

4 10 20 30 40

Expected Output

10 20 30 40 No data