Tuesday, August 22, 2017

C++11: unique_ptr

You can ensure that there is only one owner of a pointer using unique_ptr. Here is an example:

#include <iostream>
#include <memory>

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

  *ptr1 = 4;
  ptr2  = std::move(ptr1);

  std::cout << (ptr1?*ptr1:0) << " " << (ptr2?*ptr2:0) << std::endl;
  return 0;
}
// Output: 0 4
Reference: https://isocpp.org/wiki/faq/cpp11-library#unique-ptr

No comments:

Post a Comment