Skip to content

Instantly share code, notes, and snippets.

@stephenLee
Created November 16, 2012 12:46
Show Gist options
  • Select an option

  • Save stephenLee/4087071 to your computer and use it in GitHub Desktop.

Select an option

Save stephenLee/4087071 to your computer and use it in GitHub Desktop.
auto_ptr demo
// 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