#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;
}
};
void printInFunction(shared_ptr<DataStore> store) { //here count = 2
cout << "Printed in function" << endl;
store->print();
} //here count = 1
int main() {
int N;
cin >> N;
{
shared_ptr<DataStore> shr_ptr = make_shared<DataStore>(N); //here count = 1
shr_ptr->readInput();
/* here shr_ptr is passed-by-value, meaning count of share_ptr is + 1 */
printInFunction(shr_ptr);
cout << "Printed in main" << endl;
shr_ptr->print();
}
return 0;
}
Input
3 10 20 30
Expected Output
Data created Printed in function 10 20 30 Printed in main 10 20 30 Data destroyed