Chaya
Chaya

Reputation: 137

How to clone as weak pointer object in c++

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

Answers (1)

Frank Wang
Frank Wang

Reputation: 920

  1. you need init and locate memory for p and a.
  2. you need weak_p.lock() to transfer weak_ptr to shared_ptr before dereference.
  3. what you want is actually deep copy. You would need to define 'copy constructor' before deep copy one object instead of copy the reference points them.
  4. weak_ptr is not used in that way, it should be used when you have no ideal whether one object is available or not, which would be another topic.

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

Related Questions