Skip to content

Instantly share code, notes, and snippets.

@rroa
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rroa/31bdaf93255b09cc8f68 to your computer and use it in GitHub Desktop.
Save rroa/31bdaf93255b09cc8f68 to your computer and use it in GitHub Desktop.
/*
Author: Raúl Roa
Description
-----------
This program is meant to demonstrate how shared pointers allow for transfer of ownership.
Two lists contain a reference to the same pointer; remove operations are applied separately
and data integrity remains.
References
-----------
std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer.
http://en.cppreference.com/w/cpp/memory/shared_ptr
*/
#include <iostream>
#include <memory>
#include <list>
#include <cassert>
#include <algorithm>
#define SINGLE_REF 0
struct Bar;
struct Foo;
std::list<std::shared_ptr<Bar>> bars;
std::list<std::shared_ptr<Foo>> foos;
struct Bar
{
~Bar() { std::cout << "Bar desct!\n"; }
void sayHi() { std::cout << "Hi Bar\n"; }
};
struct Foo : Bar
{
void sayHi() { std::cout << "Hi Foo\n"; }
};
void Init()
{
std::shared_ptr<Foo> ptr(new Foo);
bars.push_back(ptr);
foos.push_back(ptr);
}
void Cleanup()
{
#if SINGLE_REF
bars.clear();
#else
for (std::list <std::shared_ptr<Bar>>::iterator iter = bars.begin(); iter != bars.end(); ++iter)
{
bars.remove((*iter));
break;
}
#endif
}
int main()
{
Init();
Cleanup();
#if !SINGLE_REF
for (std::list <std::shared_ptr<Foo>>::iterator iter = foos.begin(); iter != foos.end(); ++iter)
{
(*iter)->sayHi();
}
assert(foos.size() == 1);
#endif
assert(bars.size() == 0);
std::cout << "Bars: " << bars.size() << std::endl;
std::cout << "Foos: " << foos.size() << std::endl;
std::cin.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment