Is it possible to assign an weak_ptr to an existing object? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Is it possible to assign an weak_ptr to an existing object?

I don't really understand the smart pointers. how can I let the weak_ptr point to it like this: ObjectName o; weak_ptr<ObjectName> p = o; and it didn't work ... maybe I have to do something with a shared pointer?

10th May 2017, 1:07 PM
‎ɐısıօլɐ
‎ɐısıօլɐ - avatar
2 Answers
+ 2
The smart pointers are there to take ownership of an object and call delete on it when it goes out of scope. Your object o is allocated on the stack, that means that delete cannot be called on it so smart pointers cannot own it. T* t = new T; assuming that T is defined as: class T { public: ~T(){std::cout << "destroyed\n";}; }; std::unique_ptr<T> pU(std::move(t)); for example takes ownership of t and will destroy it when it goes out of scope so I don't have to call delete t; weak_ptr is not a stand alone pointer, it's an augmentation of shared_ptr a shared_ptr keeps track of a reference count and deletes it once the reference count reaches 0. a weak_ptr does not participate in the shared ownership of the pointed-to resource. There is alot more to it and I recommend that you read Effective Modern C++ by Scott Meyers which covers all of this. I also recommend that you watch these to get a gist of it Unique pointers https://www.youtube.com/watch?v=YeI6V2O5BFE Shared pointers https://www.youtube.com/watch?v=qUDAkDvoLas Weak pointers: https://www.youtube.com/watch?v=EWoMjuN5OH4 So this would compile: std::shared_ptr<T> spA(new T); std::weak_ptr<T> wpA(spA);
10th May 2017, 5:38 PM
Dennis
Dennis - avatar
+ 1
@Dennis thank you very much :)
10th May 2017, 3:31 PM
‎ɐısıօլɐ
‎ɐısıօլɐ - avatar