Effective C++: std::weak_ptr

 #include <iostream>
#include <memory>
int main()
{
 std::weak_ptr<int> wp;
 std::shared_ptr<int> sp1;
 std::shared_ptr<int> sp2;
 
 sp1 = std::make_shared<int>(5);
 wp = sp1;
 
 std::cout<<"sp1: "<<sp1.use_count()<<std::endl;
 
 if(!wp.expired()){
  std::cout<<"no"<<std::endl;
  std::cout<<"wp: "<<wp.use_count()<<std::endl;
 }
 
 sp2 = wp.lock();
 std::cout<<"One: sp1: "<<sp1.use_count()<<" sp2: "<<sp2.use_count()<<std::endl;
 
 sp1.reset();
 std::cout<<"Two: sp1: "<<sp1.use_count()<<" sp2: "<<sp2.use_count()<<std::endl;
 
 sp1 = wp.lock();
 std::cout<<"Three: sp1: "<<sp1.use_count()<<" sp2: "<<sp2.use_count()<<std::endl;
 std::cout<<"Four: wp: "<<wp.use_count()<<std::endl;
 
 std::cout<<"*sp1: "<<*sp1<<std::endl;
 std::cout<<"*sp2: "<<*sp2<<std::endl;
 
 return 0;
}

你可能感兴趣的:(Effective C++: std::weak_ptr)