1) weak_ptr<> is also a smart pointer introduced in c++11, which has a reference to an object but it does not own it.
But is it referenced by a shared_ptr. So it must be converted to shared_ptr<> ,if you want to access the referenced object.
2) std::weak_ptr is used to track the object, and it is converted to std::shared_ptr to assume temporary ownership.
3) If the original std::shared_ptr is destroyed at this time, the object's lifetime is extended until the temporary std::shared_ptr is destroyed as well.
4) std::unique_ptr models the concept of exclusive ownership, std::shared_ptr the concept of shared ownership. If I stick to this picture then std::weak_ptr models the concept of temporary ownership because it borrows the resource from a std::shared_ptr. There is one dominant reason for having a std::weak_ptr in C++: breaking of cyclic references of std::shared_ptr's.
But is it referenced by a shared_ptr. So it must be converted to shared_ptr<> ,if you want to access the referenced object.
2) std::weak_ptr is used to track the object, and it is converted to std::shared_ptr to assume temporary ownership.
3) If the original std::shared_ptr is destroyed at this time, the object's lifetime is extended until the temporary std::shared_ptr is destroyed as well.
4) std::unique_ptr models the concept of exclusive ownership, std::shared_ptr the concept of shared ownership. If I stick to this picture then std::weak_ptr models the concept of temporary ownership because it borrows the resource from a std::shared_ptr. There is one dominant reason for having a std::weak_ptr in C++: breaking of cyclic references of std::shared_ptr's.
5) Another use for std::weak_ptr is to break reference cycles formed by objects managed . If such cycle is orphaned (i,e. there are no outside shared pointers into the cycle), the shared_ptr reference counts cannot reach zero and the memory is leaked. To prevent this, one of the pointers in the cycle can be made weak.
some example:
#include <iostream>
#include <memory>
std::weak_ptr<int> gw;
void testWeakPtr()
{
//! Use count will be 1 for the first time as it is still pointed by a shared ptr
//! But once it is not pointed, i mean deleted, then use coint will be 0
//! so else block will be called.
//! to access, we need to convert it to shated_ptr by lock() method.
std::cout << "use_count == " << gw.use_count() << ": ";
if (auto spt = gw.lock()) { // Has to be copied into a shared_ptr before usage
std::cout << *spt << "\n";
}
else {
std::cout << "gw is expired\n";
}
}
int main()
{{
//! shared ptr createdauto sp = std::make_shared<int>(42);//! Now it is refered weak ptrgw = sp;testWeakPtr();
}
testWeakPtr();
return 0;}