Skip to content

Instantly share code, notes, and snippets.

@caetanus
Created November 24, 2013 22:09
Show Gist options
  • Select an option

  • Save caetanus/7633046 to your computer and use it in GitHub Desktop.

Select an option

Save caetanus/7633046 to your computer and use it in GitHub Desktop.
study case for shared_pointers. a shared_ptr<T> will destroy itself when there is no more references to it acting as a garbage collector
#include <iostream>
#include <memory>
using namespace std;
shared_ptr<int> create_new_number()
{
return shared_ptr<int>(new int(90));
}
template<class T>
void increment_number(T number)
{
(*number)++;
}
template<class T>
void sum_by(T number, int value)
{
*number += value;
}
int main()
{
auto foo = create_new_number();
cout << "initial value: " << *foo << '\n';
increment_number(foo);
cout << "incremented value: " << *foo << '\n';
sum_by(foo, 35);
cout << "added 35 to number: " << *foo << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment