64. Shared Pointer Ownership

You are working with a data object that stores values read from input.
This data must be accessed by both main() and another function.

If the object is owned by only one place, it may be destroyed too early.
To prevent this, ownership must be shared.

Your task is to use std::shared_ptr so that both main() and a function own the same object, ensuring the data remains valid until both are done using it.

What You Must Do:

  • Store input values inside a class object
  • Create the object using std::shared_ptr
  • Pass the object to a function by value to share ownership
  • Use the object in both places
  • Ensure the destructor runs only once, at the very end

Program Flow:

  1. Read N
  2. Create a data object that stores N integers
  3. Read N values into the object
  4. Pass the object to a function that prints the data
  5. Print the data again in main()
  6. Destroy the object only after both uses are complete

 

Example Input:

3
10 20 30

Example Output:

Data created
Printed in function
10 20 30
Printed in main
10 20 30 
Data destroyed

 

Constraints:

  • N ranges from 1 to 100
  • Data must be stored inside a class
  • Ownership must be shared using std::shared_ptr
  • Do not manually manage object lifetime
  • Output format must match exactly

 

 

 

Loading...

Input

3 10 20 30

Expected Output

Data created Printed in function 10 20 30 Printed in main 10 20 30 Data destroyed