Skip to content

Instantly share code, notes, and snippets.

@jstaursky
Created August 14, 2021 21:30
Show Gist options
  • Save jstaursky/1a49f8a3a3302be213457790ac51c26f to your computer and use it in GitHub Desktop.
Save jstaursky/1a49f8a3a3302be213457790ac51c26f to your computer and use it in GitHub Desktop.
#include <iostream>
#include <memory>
using namespace std;
unique_ptr<int> factory(int i)
{
return unique_ptr<int>(new int(i));
}
void client(unique_ptr<int> p)
{
// Ownership transferred into client
} // int* deleted here
int main()
{
unique_ptr<int> p = factory(2);
// *p == 2
p.reset(new int(3));
// *p == 3
client(move(p)); // ok now
// p is "null" here
if (p)
std::cout << "p is " << *p << std::endl;
else
std::cout << "p is null " << std::endl;
return 0;
}
// returns 'p is null'
// source https://howardhinnant.github.io/unique_ptr03.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment