Advertisement
Guest User

Untitled

a guest
Jul 3rd, 2015
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. class A
  2. {
  3. public:
  4. A(){}
  5. virtual void test(){std::cout << m;}
  6. int m;
  7. };
  8. int main()
  9. {
  10. A* a = new A();
  11. std::function<void ()> function = [=]()->void
  12. {
  13. //if( pointer to 'a' still valid )
  14. {
  15. a->test();
  16. }
  17. };
  18. delete a;
  19. //or if( pointer to 'a' still valid )
  20. function();
  21.  
  22. system("pause");
  23. return 0;
  24. }
  25.  
  26. std::shared_ptr<A> a(new A());
  27. std::weak_ptr<A> weak_a(a);
  28. std::function<void ()> function = [weak_a]()->void
  29. {
  30. if( std::shared_ptr<A> a = weak_a.lock() )
  31. {
  32. // to get the A* from a, do a.get()
  33. // operator-> and *a work however:
  34. a->test();
  35. }
  36. };
  37. a.reset(); // instead of delete
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement