Tuesday, August 22, 2017

C++11: shared_ptr

You can safely share a pointer using shared_ptr. Here is an example:

#include <iostream>
#include <memory>

int main()
{
  std::shared_ptr<int> ptr1(new int());
  std::shared_ptr<int> ptr2;

  *ptr1 = 4;
  ptr2  = ptr1;

  std::cout << (ptr1?*ptr1:0) << " " << (ptr2?*ptr2:0) << " ";

  ptr1.reset();
  std::cout << (ptr1?*ptr1:0) << " " << (ptr2?*ptr2:0) << " ";

  ptr2.reset();
  std::cout << (ptr1?*ptr1:0) << " " << (ptr2?*ptr2:0) << std::endl;

  return 0;
}
// Output: 4 4 0 4 0 0
Reference: https://isocpp.org/wiki/faq/cpp11-library#shared-ptr

No comments:

Post a Comment