#include <iostream>
#include <memory>
int main()
{
std::shared_ptr<int> sptr1(new int());
std::shared_ptr<int> sptr2;
std::weak_ptr<int> wptr1;
////
*sptr1 = 4;
sptr2 = sptr1;
std::cout << (sptr1?*sptr1:0) << " " << (sptr2?*sptr2:0) << " ";
wptr1 = sptr1;
auto sptr3 = wptr1.lock();
std::cout << (sptr3?*sptr3:0) << std::endl;
wptr1.reset();
////
sptr1.reset();
std::cout << (sptr1?*sptr1:0) << " " << (sptr2?*sptr2:0) << " ";
wptr1 = sptr2;
auto sptr4 = wptr1.lock();
std::cout << (sptr4?*sptr4:0) << std::endl;
wptr1.reset();
////
sptr2.reset();
std::cout << (sptr1?*sptr1:0) << " " << (sptr2?*sptr2:0) << " ";
wptr1 = sptr2;
auto sptr5 = wptr1.lock();
std::cout << (sptr5?*sptr5:0) << std::endl;
wptr1.reset();
////
return 0;
}
/* Output:
4 4 4
0 4 4
0 0 0
*******/
Reference: https://isocpp.org/wiki/faq/cpp11-library#weak-ptr
Tuesday, August 22, 2017
C++11: weak_ptr
A weak_ptr is a kind of pointer that can share access to a pointer, but does not have a say in when the pointed to object is deleted. Here is an example:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment