Effective Modern C ++: smart pointers (three)

4:std::weak_ptr

 

std :: weak_ptr from shared_ptr produce, features:

  • std::weak_ptr Is a smart pointer, it is  std :: existence of non-owners ( "weak") shared_ptr managed object reference. You must be converted to an object before accessing the referenced  std :: shared_ptr.
  • std::weak_ptr It used to express the concept of temporary ownership: only when there is an object only needs to be accessed, and when others may be deleted at any time, can be used  std::weak_ptr to track the object. When required to obtain a temporary title, it will convert it to  std :: shared_ptr, at this time if the original  std :: shared_ptr is destroyed, then the lifetime of the object will be extended to the temporary  std :: shared_ptr likewise destroyed.
  • std :: weak_ptr not increase the reference count

std :: weak_ptr lock () method can obtain its corresponding shared_ptr, shared_ptr if the null pointer is returned it has been destructed this time, calling lock () to create a shared_ptr i.e., reference will therefore reference count +

Sample code:

 1 #include <iostream>
 2 #include <memory>
 3  
 4 std::weak_ptr<int> gw;
 5  
 6 void f()
 7 {
 8     if (auto spt = gw.lock()) { // 使用之前必须复制到 shared_ptr
 9     std::cout << *spt << "\n";
10     }
11     else {
12         std::cout << "gw is expired\n";
13     }
14 }
15  
16 int main()
17 {
18     {
19        auto sp = std::make_shared<int>(42);
20       gw = sp;
21  
22       f();
23     }
24  
25     f();
26 }

"Effective Modern C ++" in typical applications:

1 std::shared_ptr<const Widget> fastLoadWidget(WIDGET_ID id){
2     static std::unordered_map<WIDGET_ID, std::weak_ptr<Widget> > cache;
3     auto objPtr = cache[id].lock();
4     if (!objPtr) {
5         objPtr = loadWidget(id);
6         cache[id] = objPtr;
7     }
8     return objPtr;
9 }

 

Guess you like

Origin www.cnblogs.com/Asp1rant/p/12500286.html