Last active
January 4, 2016 06:45
-
-
Save mkolod/38f450bc579cbffce885 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.