Created
November 16, 2012 12:46
-
-
Save stephenLee/4087071 to your computer and use it in GitHub Desktop.
auto_ptr demo
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
| // avoid resource leaks when exceptions are thrown. | |
| // if an exception occurs after successful memory allocation but | |
| // before the delete statement executes, a memory leak could occur. | |
| // void memory_leak() | |
| //{ | |
| // ClassA * ptr = new ClassA; | |
| // try { | |
| // ... | |
| // } | |
| // catch(...) { | |
| // delete ptr; | |
| // throw; | |
| // } | |
| // delete ptr; | |
| //} | |
| #include <iostream> | |
| #include <memory> | |
| using namespace std; | |
| class Double { | |
| public: | |
| Double(double d = 0) : dValue(d) { cout << "constructor: " << dValue << endl; } | |
| ~Double() { cout << "destructor: " << dValue << endl; } | |
| void setDouble(double d) { dValue = d; } | |
| private: | |
| double dValue; | |
| }; | |
| int main() { | |
| auto_ptr<Double> ptr(new Double(3.14)); | |
| (*ptr).setDouble(6.28); | |
| return 0; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment