Advertisement
Guest User

Dangerous use of bare reference to shared_ptr owned object

a guest
Mar 8th, 2013
372
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1.  
  2. #include "boost/date_time.hpp"
  3.  
  4. #include <iostream>
  5. #include <string>
  6. #include <thread>
  7.  
  8. namespace
  9. {
  10.   class Example
  11.   {
  12.   public: // interface
  13.     Example() : test_(new int(7)){}
  14.     ~Example()
  15.     {
  16.       std::cout << "~Example" << std::endl;
  17.       delete test_;
  18.       test_ = nullptr;
  19.     }
  20.  
  21.     void explode()
  22.     {
  23.       std::cout << "TEST: " << *test_ << std::endl;
  24.     }
  25.  
  26.   private: // data
  27.     int* test_;
  28.   }; // class
  29.  
  30.  
  31.   void printVal(Example& val)
  32.   {
  33.     std::this_thread::sleep_for(std::chrono::milliseconds(5000));
  34.     std::cout << "Accessing reference to shared_ptr owned object" << std::endl;
  35.     val.explode();
  36.   }
  37.  
  38. } // namespace
  39.  
  40. int main(int argc, char** argv)
  41. {
  42.   auto sharedInt = std::make_shared<Example>();
  43.   std::thread printThread(&printVal, std::ref(*sharedInt) );
  44.  
  45.   sharedInt.reset();
  46.  
  47.   std::this_thread::sleep_for(std::chrono::milliseconds(10000));
  48.  
  49. } // main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement