60. unique_ptr Ownership Transfer

A resource managed by std::unique_ptr must have exactly one owner at any moment.

In this problem, ownership of a dynamically allocated buffer must be explicitly transferred from one std::unique_ptr to another. The provided template code attempts to create a second owner for the same resource, which violates std::unique_ptr ownership rules and causes a compilation error.

Your task is to restructure the ownership flow so that the resource always has a single owner, the program compiles successfully, and the runtime behavior matches the expected output.

This problem emphasizes ownership semantics and lifetime control, not syntax tricks.

Program Flow:

  1. Read an integer N
  2. Allocate a buffer of size N using std::unique_ptr
  3. Read N integer values into the buffer
  4. Transfer ownership of the buffer to another std::unique_ptr
  5. Print the buffer contents using the new owner
  6. Verify that the original owner no longer owns the resource

 

Example Input:

4
10 20 30 40

Example Output:

10 20 30 40
No data 

 

Constraints:

  • N ranges from 1 to 100
  • The buffer elements are integer values that fit within uint8_t
  • There must never be two owners of the same resource
  • Ownership transfer must be explicit
  • The output format must match exactly, including spacing and newlines
  • No memory leaks or undefined behavior are allowed

 

 

 

Loading...

Input

4 10 20 30 40

Expected Output

10 20 30 40 No data