#include <iostream> #include <memory> #include <vector> using namespace std; class DataStore { vector<int> data; public: DataStore(int n) : data(n) { cout << "Data created" << endl; } ~DataStore() { cout << "Data destroyed" << endl; } void readInput() { for (int& v : data) { cin >> v; } } void print() const { for (size_t i = 0; i < data.size(); i++) { cout << data[i]; if (i + 1 < data.size()) cout << " "; } cout << endl; } }; // This function must SHARE ownership of DataStore void printInFunction(shared_ptr<DataStore> dptr) { cout << "Printed in function" << endl; dptr->print(); } int main() { int N; cin >> N; { // Create DataStore using shared_ptr shared_ptr<DataStore> ptr(new DataStore(N)); // Read input into DataStore ptr->readInput(); // Pass DataStore to printInFunction() printInFunction(ptr); cout << "Printed in main" << endl; // Print data again here ptr->print(); } return 0; }
Test Cases
Test Results
Input
3 10 20 30
Expected Output
Data created Printed in function 10 20 30 Printed in main 10 20 30 Data destroyed