I have recently started learning shared pointers and need some help.
#include <bits/stdc++.h>
using namespace std;
class A
{
public:
int a;
A (int x) {
a = x;
}
int print() {
return a;
}
};
int main()
{
shared_ptr<vector<shared_ptr<A>>> vec1 = make_shared<vector<shared_ptr<A>>>(1);
(*vec1)[0] = make_shared<A>(50);
shared_ptr<vector<shared_ptr<A>>> vec2 = make_shared<vector<shared_ptr<A>>>();
vec2->push_back((*vec1)[0]);
for (shared_ptr<A>& obj : *vec2) {
obj = make_shared<A>(100);
}
cout << (*((*vec1)[0])).a;
return 0;
}
This gives the output as 50 while I expected it to be 100. Can some please explain why? And what can I do to get this as 100? TIA!
Aucun commentaire:
Enregistrer un commentaire