Skip to content

Instantly share code, notes, and snippets.

@mkolod
Last active January 4, 2016 06:45
Show Gist options
  • Select an option

  • Save mkolod/38f450bc579cbffce885 to your computer and use it in GitHub Desktop.

Select an option

Save mkolod/38f450bc579cbffce885 to your computer and use it in GitHub Desktop.
// Demo of automatic memory management in C++ using smart pointers.
#include <iostream>
#include <sstream>
using namespace std;
#define SpFoo shared_ptr<Foo>
class Foo {
private:
const int i;
const double d;
public:
// constructor
Foo(const int i, const double d):
i(i), d(d) {
cout << "Creating " << toString() << endl;
}
// destructor
~Foo() {
cout << "Destroying " << toString() << endl;
}
// pretty print
string toString() const {
ostringstream strs;
strs << "Foo(" << i << ", " << d << ")";
return strs.str();
}
friend ostream& operator<<(ostream&, const Foo&);
};
ostream& operator<<(ostream &strm, const Foo& foo) {
return strm << foo.toString() << endl;
}
/* This shows the allocation of the object on the heap.
The caller would normally need to manage memory using delete,
but not with shared_ptr. */
SpFoo createFoo(const int i, const double d) {
return SpFoo(new Foo(i, d));
}
int main() {
/* auto = type inference
Allocate Foo on the heap in createFoo,
then return it to the caller (to main) */
auto foo = createFoo(1, 2.0);
/* Free up reference to demonstrate the automatic call of the destructor.
This could also be done using the call to reset() on the shared_ptr.
If we don't do this, the printing will be out of sequence, though the reassignment
of shared_ptr will still eventually result in the destruction of the object.
The clearing of shared_ptr before reassignment will clean up the
create-destroy-create printing sequence. */
foo = NULL;
foo = createFoo(3, 4.0);
// let's dereference the pointer and do some stuff with it
cout << "Dereferencing pointer: " << *foo;
return 0;
}
@mkolod
Copy link
Author

mkolod commented Jan 4, 2016

The display should be as follows.:

Creating Foo(1, 2)
Destroying Foo(1, 2)
Creating Foo(3, 4)
Dereferencing pointer: Foo(3, 4)
Destroying Foo(3, 4)

The second destruction happens because the process is terminating,
but the first one definitely shows automatic memory management.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment