Reputation: 137
how to clone weak pointer??
class Distance
{
public:
int height;
};
main()
{
weak pointer <Distance> p;
p->height = 12;
weak pointer <Distance> a;
a = p;
a->height = 34;
}
here when a->height is 10,then even p->height becomes 10.i don't want height of object p to chance. Can anyone tell how clone weak pointer?
Upvotes: 1
Views: 2300
Reputation: 920
Full example would be :
#include <iostream>
#include <memory>
using std::weak_ptr;
class Distance {
public :
int height;
Distance(int h) {height = h;}
Distance(const Distance& rhs) {
height = rhs.height;
}
};
int main()
{
weak_ptr<Distance> p = std::make_shared<Distance>(12);
weak_ptr<Distance> a(p);
auto ps = p.lock();
weak_ptr<Distance> b = std::make_shared<Distance>(*ps);
auto as = a.lock();
auto bs = b.lock();
std::cout << ps->height << as->height << bs->height << std::endl;
}
Upvotes: 2